The checkbox field creates a list of tick-able options. This field is useful to add categories or other information to your post or page.
Creating a checkbox field
The checkbox field contains options to customize your field:
- Choices: You can populate the tick-able list with choices. Each choice is entered on a new line. Each choice requires a value and a label which are broken by a ‘:’. If no ‘:’ is found, the field will use the Label as the Value.
Edit screen
Template usage
The API returns different data to these functions:
- get_field: an array of values
- the_field: a string containing all values separated by a comma
<?php /* * Displaying single value */ ?> <p>Color: <?php the_field('field_name'); ?></p> <?php /* * Displaying a single value's Label */ $field = get_field_object('field_name'); $value = get_field('field_name'); $label = $field['choices'][ $value ]; ?> <p>Color: <?php echo $label; ?></p> <?php /* * Displaying multiple values */ ?> <p>Colors: <?php echo implode(', ', get_field('field_name')); ?></p> <?php /* * Conditional statement (Checkbox rvalue is an array) */ if( in_array( 'red', get_field('field_name') ) ) { //... } /* * Query posts for a checkbox value. * This method uses the meta_query LIKE to match the string "red" to the database value a:2:{i:0;s:3:"red";i:1;s:4:"blue";} (serialized array) * The above value suggests that the user selected "red" and "blue" from the checkbox choices */ $posts = get_posts(array( 'meta_query' => array( array( 'key' => 'field_name', // name of custom field 'value' => '"red"', // matches exaclty "red", not just red. This prevents a match for "acquired" 'compare' => 'LIKE' ) ) )); if( $posts ) { //... } ?>




