Support

Account

Home Forums ACF PRO WP_query using meta_query for an ACF checkbox field

Solved

WP_query using meta_query for an ACF checkbox field

  • Hi everyone,

    I’m using WP_Query to show a list of results. I want to filter these based on an ACF checkbox field. I think that I’m getting muddled up with how to correctly parse the ‘value’ array from my ACF field.

    My code:

    <?php 
    	
    $my_acf_checkbox_field_arr = get_field('my_checkbox');
    
    // args
    $args = array(
    	'numberposts'	=> -1,
    	'post_type'		=> 'my-cpt',
    	'meta_query' => array(
    		array(
    			'key'     => 'my_checkbox',
    			'value'   => $my_acf_checkbox_field_arr,
    			'compare' => 'IN',
    		),
    	),
    );
    
    // query
    $the_query = new WP_Query( $args );
    
     if( $the_query->have_posts() ):
     while( $the_query->have_posts() ) : $the_query->the_post();
     	echo the_title(); 
     endwhile;
     endif;
    
     wp_reset_query();
  • Hi @ryandorn

    I believe you should be able to do it like this:

    // Get the selected options
    $my_acf_checkbox_field_arr = get_field('my_checkbox');
    
    // Build the meta query based on the selected options
    $meta_query = array('relation' => 'OR');
    foreach( $my_acf_checkbox_field_arr as $item ){
        $meta_query[] = array(
            'key'     => 'checkbox',
            'value'   => $item,
            'compare' => 'LIKE',
        );
    }
    
    // args
    $args = array(
    	'numberposts'	=> -1,
    	'post_type'		=> 'my-cpt',
    	'meta_query' => $meta_query,
    );
    
    $the_query = new WP_Query( $args );

    I hope this helps 🙂

  • That did the trick, thanks James!

  • Given answer has potential to give false positives.

    E.g. you’re after posts with IDs 528 and 76, but there are also posts with IDs 5287, 4528, 765 and 2769 which you don’t intent to get, but they might happen to match the rest of the query.

    The same is true to any values, since matching “apple” will give you false positive on “apple_pie” or “applejuice” etc.

    Internally arrays are serialized and look like

    
    a:4:{i:0;s:3:"528";i:1;s:5:"15289";i:2;s:5:"apple";i:3;s:9:"apple_pie";}
    

    note double quotes around values – which you can use to make sure that you’re matching exactly what you want

    To safely query for values in them, just include quotation around value you’re after:

    
    $meta_query[] = array(
        'key'     => 'checkbox',
        'value'   => sprintf('"%s"', $item),
        'compare' => 'LIKE',
    );
    

    You can also add colon before and semicolon after to explicitly telegraph your intention to query serialized value:

    
    'value'   => sprintf(':"%s";', $item),
    
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘WP_query using meta_query for an ACF checkbox field’ is closed to new replies.