If you work with forms in PHP, you often have to write code like this snippet:
<option value="<?php echo esc_attr( $value ) ?>" <?php echo ($value == $other_value) ? 'selected' : '' ?>>
Luckily WordPress provides three functions that help with such tasks:
checked() for radio buttons and checkboxes.
selected() for options in select elements.
disabled() for input elements that can be disabled.
All three functions use the same private helper function (namely
__checked_selected_helper). This means the way they work, as well as their parameters, are identical:
$value (required): The value that you want to compare.
$current (optional): Value to compare to. Defaults to true if not set.
$echo (optional): Output or return the generated HTML. Defaults to true if not set.
You either pass in a single value, or two values. If the comparison returns true, the correct HTML will either be outputted or returned, depending on the third parameter.
Let’s have a look at some code examples.
<input type="checkbox" name="x" value="1" <?php checked( $x ); ?> /> Is x true?
In this case if
$x contains a value that evaluates to
$x evaluates to
false, nothing will be outputted and the checkbox won’t be checked.
<option value="apple" <?php selected( $fruit, 'apple' )?>>Apple</option>
<option value="orange" <?php selected( $fruit, 'orange' )?>>Orange</option>
Here we compare two values to determine whether an option needs to be selected or not. We use a string here as second parameter, but it could be a variable as well.
$x = 1;
$y = 2;
$string = '<input type="radio" name="math" value="1"' . disabled( $x, $y, false ) . ' />';
In this third example, we have passed two variables to the
disabled() function and passed
false as third parameter. This will return the HTML generated by the function instead of outputting it.
$y are not equal, the radio button is active. If
$y were equal, the button would be disabled.
There you have it! Three functions that save keystrokes and make your code a lot cleaner.