[+] Programmatically check or uncheck checkboxes field options or retrieve an option value

There is no official API to set types fields and checkboxes fields are stored in a proprietary format that makes them difficult to manipulate.

You can use this unofficial function to retrieve the value for a checkboxes option (to see if it is checked or not), or to check or uncheck a particular checkboxes option.

Note that the recommended settings for checkboxes fields are to save nothing to the database when unchecked, which this code assumes.

/**
 * Unofficial API function to check/uncheck checkboxes options
 * 
 * @param int $post_id
 * @param string $field // slug of checkboxes field
 * @param string $option // title of checkbox option to manipulate
 * @param string $action : 'check' | 'uncheck' | 'value' (default, returns current value)
 * 
 * Important: assumes recommended checkboxes setting of save nothing to database when unchecked
 */

function ts_checkboxes( $post_id, $field, $option, $action = 'value' ){

    if ( isset($post_id) && isset($field) && isset($option) ){

		$field_settings = types_get_field( $field );
		
        $field_options = $field_settings['data']['options'];

		// Locate the option key
        $key = array_search( $option, array_column( $field_options, 'title' ) );
        $keys = array_keys( $field_options );
		$option_key = $keys[$key];

		// Get the current post meta value
		$meta = get_post_meta( $post_id, 'wpcf-'.$field, true );

		// If action = 'value' just return the value
		if ( $action == 'value' && isset( $meta[$option_key] ) ){
			return $meta[$option_key][0];
		} else {
			// Remove the existing key if it exists (i.e. uncheck)
			// because recommended setting is to save nothing when unchecked
			unset( $meta[$option_key] );
			
			// If $checked == true then add back the key + value
			if ( $action == 'check' ){
				$meta[$option_key] = array($field_options[$option_key]['set_value']);
			}
			update_post_meta( $post_id, 'wpcf-'.$field, $meta );		
		}
    }
}

By way of examples:

// 1. Get the value of the option "Second checkbox" of a checkboxes field "Available options" from the current post:
global $post;
$value = ts_checkboxes( $post->ID, 'available-options', 'Second checkbox' );
 
// 2. set the same option as checked
global $post;
ts_checkboxes( $post->ID, 'available-options', 'Second checkbox', 'check' );
 
// 3. set the same option as unchecked
global $post;
ts_checkboxes( $post->ID, 'available-options', 'Second checkbox', 'uncheck' );

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments