This post is part of the ClassicPress Plugin Development series in which I am going to look at both best practice for developing plugins and how I approach some requirements as well as some of the functions I commonly use.
Text fields and textareas are good for accepting arbitrary input, but many plugin settings are simply on or off. For those, a checkbox is the right control. The checkbox is a little more involved than a text field because of the way HTML forms handle unchecked checkboxes.
The example I am using in this post is derived from my Remove Revisions plugin which uses a PHP namespace.
namespace azurecurve\RemoveRevisions;
A checkbox input uses the checked attribute to indicate whether it is ticked. ClassicPress provides the checked() helper function for this, which compares two values and outputs the checked attribute if they match. This avoids writing a ternary or if/else statement in the template.
The label text is localised with esc_html_e() as covered in the post on developing for translation. The value attribute of the checkbox is always 1, which is what will be submitted if the box is ticked.
<table class="form-table">
<tr>
<th scope="row">
<?php esc_html_e( 'Enable Feature', 'azrcrv-rr' ); ?>
</th>
<td>
<label for="enable-feature">
<input type="hidden" name="enable-feature" value="0" />
<input
type="checkbox"
name="enable-feature"
id="enable-feature"
value="1"
<?php checked( 1, $options['enable-feature'] ); ?>
/>
<?php esc_html_e( 'Enable this feature', 'azrcrv-rr' ); ?>
</label>
<p class="description">
<?php esc_html_e( 'Tick to enable the feature.', 'azrcrv-rr' ); ?>
</p>
</td>
</tr>
</table>
The label wraps the input, which means clicking the label text also toggles the checkbox — a small but worthwhile accessibility improvement, which was covered in more detail in the post on developing for accessibility.
You will also notice a hidden input immediately before the checkbox. When a checkbox is unticked, browsers do not submit it at all. This means that in your save function, the field will simply be absent from $_POST when the box is unticked, making it difficult to distinguish between “the user unticked this” and “this field was not on the form at all”.
The solution is the hidden input with the same name and a value of 0. When the checkbox is unticked, the browser submits the hidden field’s value of 0. When the checkbox is ticked, the browser submits the checkbox’s value of 1, overriding the hidden field. This gives your save function a reliable value in either case.
If there is a topic which fits the typical ones of this site, which you would like to see me write about, please use the form, below, to submit your idea.


