Friday, 3 June 2011

WordPress Form Helper Functions

Setting the state of checkboxes, radio buttons and selected items in dropdown lists in html forms can become tiresome, so I was pleased to recently discover WordPress has some built-in helper functions. I've found these to be pretty handy in building admin forms for Wordpress plugins and hopefully they can save you some time too.

checked( $checked, $current = true, $echo = true )

This function compares two given values (for example, a saved option vs. one chosen in a form) and, if the values are the same, adds the checked attribute to the current radio button or checkbox. This is essentially the same as comparing values with if(), but results in more concise code. The third parameter determines if the result is echoed or just returned which is handy if you are concatenating to a string, etc.

This function has been defined since WordPress v1.0 and is documented here.


selected( $selected, $current = true, $echo = true )

This function is for use in dropdown form fields. Compares two given values (for example, a saved option vs. one chosen in a form) and, if the values are the same, adds the selected attribute to the current option tag. Again, the third parameter determines if the result is echoed or just returned which is handy if you are concatenating to a string, etc.

This function has been defined since WordPress v1.0 and is documented here.


disabled( $disabled, $current = true, $echo = true )

This function compares two given values (for example, a saved option vs. one chosen in a form) and, if the values are the same, adds the disabled attribute to a form input field. Again, the third parameter determines if the result is echoed or just returned which is handy if you are concatenating to a string, etc.

This function was not defined until WordPress v3.0 and is documented here.

These functions are all located in wp-includes/general-template.php.