1

I have a custom post type and can get them using WP_Query with the following array:

$args = array(  
       'post_type' => 'projects',
       'post_status' => 'publish',
       'posts_per_page' => 10,
   );

This works fine but now I have added a new field to the post type called 'featured_project' which is a checkbox with the value of 1, so to get only results with the checkbox checked I have added a meta_query, but with this meta_query I get no results and can't figure out why:

$args = array(  
       'post_type' => 'projects',
       'post_status' => 'publish',
       'posts_per_page' => 10,
       'meta_query' => array(
        'relation' => 'AND',
            array(
                'key'     => 'featured_project',
                'value'   => 1,
                'compare' => '=',
            ),
        )
   );

I don't know why, I have googled this time and again and my code looks correct I think but with the meta_query addition I just get an empty set, could anyone please advise? I'm using WordPress v5, php 7.1

I have just tried a new array format and changed the value of the 'featured_project' checkbox to 'featured', and still got no results.

   $args = array(  
       'post_type' => 'projects',
       'post_status' => 'publish',
       'posts_per_page' => 10,
       'meta_query' => array(
            array(
                'key'     => 'featured_project',
                'value'   => 'featured',
                'compare' => '=',
            )
        )
   );

And tried:

$args = array(  
       'post_type' => 'projects',
       'post_status' => 'publish',
       'posts_per_page' => 10,
       'meta_query' => array(
        'relation' => 'AND',
            array(
                'key'     => 'featured_project',
                'value'   => 'featured',
                'compare' => '=',
            ),
        )
   );
0

Your code looks correct. Have you checked your stored meta data to confirm the value stored is 1? Also, have you tried comparing to a string value, eg '1' instead of 1? Just a stab in the dark, but worth a shot.

Assuming your stored values are correct, and seeing as the values can only ever be 1, you could try using:-

'compare' => 'LIKE'

LIKE usually works as a partial match, but in your case, it shouldn't make any difference.

  • Yes I finally realised that it was the way I had set the return value in the custom field, it's working now. – Barry Poore Dec 16 '18 at 21:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.