Using WordPress ‘disabled()’ PHP function

The disabled() WordPress PHP function outputs the HTML disabled attribute. It compares the first two arguments and if they’re identical, it marks the attribute as disabled.

Usage

Here’s a basic usage of the disabled() function:

$disable_element = true;
echo '<input type="text" ';
disabled( $disable_element, true );
echo ' name="sample_text_field" />';

In this example, if $disable_element is true, the input field will be disabled.

Parameters

  • $disabled (mixed): Required. One of the values to compare.
  • $current (mixed): Optional. The other value to compare if not just true. Default: true.
  • $display (bool): Optional. Whether to echo or just return the string. Default: true.

More information

See WordPress Developer Resources: disabled()
This function was implemented in WordPress 3.0.

Examples

Disabling a Text Input Field

$disable_field = true;
echo '<input type="text" ';
disabled( $disable_field, true );
echo ' name="my_text_field" />';

This will disable the text input field if $disable_field is true.

Disabling a Checkbox

$disable_checkbox = true;
echo '<input type="checkbox" ';
disabled( $disable_checkbox, true );
echo ' name="my_checkbox" />';

This will disable the checkbox if $disable_checkbox is true.

Disabling a Button

$disable_button = false;
echo '<button ';
disabled( $disable_button, true );
echo '>My Button</button>';

This will keep the button enabled as $disable_button is false.

Comparing Two Values

$user_role = 'admin';
$required_role = 'admin';
echo '<button ';
disabled( $user_role, $required_role );
echo '>Admin Button</button>';

This will disable the button if $user_role does not match $required_role.

Returning Disabled Attribute Instead of Echoing

$should_disable = true;
$disabled_attribute = disabled( $should_disable, true, false );
echo '<button ' . $disabled_attribute . '>Test Button</button>';

This will return the ‘disabled’ attribute string instead of echoing it directly. If $should_disable is true, the button will be disabled.