This one’s for developers! If you’re using checkboxes, radio buttons, or dropdowns in your theme or plugin options, you might have overlooked some very useful functions that aren’t listed in the Codex: checked()
, selected()
, and disabled()
. These allow you to compress the code required to see whether or not the relevant option has already been selected, or whether the form option should be disabled. This results in much more readable code.
// Testing the value with if() <input type="checkbox" checked="checked" name="options[postlink]" value="1" /> /> // Using checked() instead <input type="checkbox" checked="checked" name="options[postlink]" value="1" /> />
Checked()
works with radio buttons as well as checkboxes.
In a long list of dropdown options, the difference with selected()
is even more striking.
// Testing the value with if() <select name="options[content]"><option title="" selected="selected" value="title">>Title Only</option><option selected="selected" value="excerpt">>Title and Excerpt</option><option value="content"> echo 'selected="selected"'; ?>>Title and Content</option> </select> // Using selected() instead <select name="options[content]"><option title="" selected="selected" value="title">>Title Only</option><option selected="selected" value="excerpt">>Title and Excerpt</option><option selected="selected" value="content">>Title and Content</option> </select>
The third function, disabled()
, is used to disable a button if the two given values match. Here’s an example from the core:
// using if() <input id="hostname" type="text" name="hostname" value="<?php echo esc_attr($hostname); if ( !empty($port) ) echo " />"<!--?php if ( defined('FTP_HOST') ) echo ' disabled="disabled"' ?--> size="40" /> // using disabled() instead <input id="hostname" type="text" name="hostname" value="<?php echo esc_attr($hostname); if ( !empty($port) ) echo " />"<!--?php disabled( defined('FTP_HOST') ); ?--> size="40" />
Find all the WordPress Hidden Gems in WordPress for Web Developers.
Barrett Golding says
Thanks loads for this. Put it to immediate use.
Your
checked()
above might need a minor correction tho: there’s a black space before the php (after thevalue=
).That space isn’t needed, as it’s conditionally added by WP’s
__checked_selected_helper()
. If match is true, that function returns:" $type='$type'"
(where $type equals'selected'
,'checked'
or'disabled'
). So that space will be writ if needed.Your selected() and disabled() examples above, correctly, do not have that space.
Again, thanks much for this, and the other hidden gems you’ve revealed.
Prasad says
These were really unknown (at least to me really)…thanks for sharing..!!
kathy says
wow- i’ve wasted quite a bit of time doing that the old way.
xiangzi says
you should use it like this
checked(1,$options['postlink']);
Morten says
I don’t get it. Isn’t there something wrong with those lines of code? You don not seem to be using either of the functions mentioned…