WordPress Checked and Selected Functions

Two of my favorite functions in WordPress are the checked() and selected() functions. Both of these functions are extremely useful whenever you are working with form elements in your plugins and themes so it helps to understand both of these little nuggets of goodness. These two functions are used the same way, but output different results.

The selected() function compares two values in a select list and if they are identical will set the current option value to selected. This is useful when displaying form fields (an options page for example) and want to determine whether an option is set or not. Lets look at an example:

<select>
    <option value="red" <?php selected( $option_value, 'red' ); ?>>Red</option>
    <option value="orange" <?php selected( $option_value, 'orange' ); ?>>Orange</option>
    <option value="blue" <?php selected( $option_value, 'blue' ); ?>>Blue</option>
</select>

Assuming the $option_value variable is equal to the value of “orange”, the following HTML would be generated

<select>
    <option value="red">Red</option>
    <option value="orange" selected="selected">Orange</option>
    <option value="blue">Blue</option>
</select>

The checked() function works exactly the same, in that it compares the two values and if they are identical it sets the current checkbox form element to be checked.

<input type="checkbox" name="rage_mode" <?php checked( $rage_mode, 'on' ); ?>/> Rage Mode<br /> 
<input type="checkbox" name="ninja_mode" <?php checked( $ninja_mode, 'on' ); ?> /> Ninja Mode<br /> 
<input type="checkbox" name="zombie_mode" <?php checked( $zombie_mode, 'on' ); ?> /> Zombie Mode<br /> 

Let’s assume that Rage mode and Zombie mode are activated. The following HTML would be generated:

<input type="checkbox" name="rage_mode" checked="checked"/> Rage Mode<br /> 
<input type="checkbox" name="ninja_mode"/> Ninja Mode<br /> 
<input type="checkbox" name="zombie_mode" checked="checked"/> Zombie Mode<br /> 

There is also a lesser know function in WordPress called disabled(). This function checks two values and if identical returns the disabled attribute for any HTML element.

For more information on these functions, and many more useful WordPress functions, check out my newest book: Professional WordPress Third Edition.