Home > Enterprise >  Custom post type query by metabox value
Custom post type query by metabox value

Time:12-05

I've created a custom post type for "portfolio" with a custom metabox with a lot of extra fields, one of which is a checkbox that I'm using to determine whether this post type contains a case study, but I've hit a snag and I can't see where I've gone wrong. The output for the checkbox is either 'yes' or ''.

The setup in my metabox build is:

<input type="checkbox" name="rccustom_fields[case_study]" value="yes" <?php if ( isset($meta['case_study']) && $meta['case_study'] === 'yes' ) echo 'checked'; ?>>

And I can see the values exist as expected by outputting:

$meta = get_post_meta( $post->ID, 'rccustom_fields', true );
 print_r($meta);

BUT, when I pull a basic WP query with args to filter those results:

$args = array(
'numberposts'   => -1,
'post_type'     => 'portfolio',
'meta_key'      => 'case_study',
'meta_value'    => 'yes',

I get nothing returned, even though doing the print_r shows me that the meta value does indeed exist and is equal to 'yes'. (if I comment out the meta_key/meta_value lines, all posts from the custom post type do display)

Anybody see something I don't here?

CodePudding user response:

Try below code , It may help to you.

$args_portfolio = array (
    'post_type' => 'portfolio',
    'posts_per_page' => -1,
    'post_status' => 'publish',
    'meta_query' => array(
        array(
            'key' => 'case_study',
            'value' => 'yes',
            'compare' => '=',
        ),
    ),
);

$data_portfolio = new WP_Query( $args_portfolio );

CodePudding user response:

Incase it helps anyone... I wasn't able to find an elegant way to incorporate this additional filter into my query, but because the custom post type for this project will have very few (less than 30) posts, I opted to simply add an IF statement inside my loop to filter for only posts matching the case_study field:

$portfolio_query = new WP_Query( $args_portfolio );

if( $portfolio_query->have_posts() ) :

    echo '<ul>';

    while( $portfolio_query->have_posts() ) : $portfolio_query->the_post();
        
    $meta = get_post_meta( $post->ID, 'rccustom_fields', true );

        if ( isset($meta['case_study'] )) :
            the_title();
        endif;

    endwhile;

    echo '</ul>';

endif;

It feels clunky to me to do it this way rather than finding a way to filter the query, but in the interest of moving on with this page, it do.

  • Related