Support

Account

Home Forums ACF PRO Dynamically Query Posts by Checkbox Values

Solved

Dynamically Query Posts by Checkbox Values

  • I have a CPT that has a Checkbox field. On the CPT’s single template I want to query other posts in the same CPT that have at least one of the same checkbox values selected. Basically I’m creating a list of other posts that are “like” this one…based off the checkbox selection.

    Here is what I have so far, but is not working. It’s retrieving all posts in the same CPT, just not those that have at least one of the same values selected.

    $subjects = get_field('subjects'); //checkbox field, return format value only
    
    $meta_query = array('relation' => 'OR');
    foreach( $subjects as $subject ) :
        $meta_query[] = array(
            'key' => 'subjects',
            'value' => $subject,
            'compare' => 'LIKE',
        );
    endforeach;
    
    $resource_args = array(
        'post_type' => 'resources',
        'posts_per_page' => -1,
        'meta_query' => $meta_query,
    );
    
    $resource_query = new WP_Query($resource_args);

    When I loop through the query, it returns all posts in the resources cpt, even some of the posts that don’t have any of the same checkbox values selected.

    I’ve also tried

    
    $resource_args = array(
        'post_type' => 'resources',
        'posts_per_page' => -1,
        'meta_key' => 'subjects',
        'meta_value' => $subjects, // also tried array($subjects)   
    );
    

    But this causes an error and breaks the page.

    Any help would be greatly appreciated.

  • This post was marked as spam, so I had recreated the same topic at https://support.advancedcustomfields.com/forums/topic/query-posts-by-checkbox-value-dynamically/ where it was solved.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.