0

I'm currently working on a widget which returns a single random featured property on a website but I'm having some trouble with my WP_Query arguments.

In the backend I have 2 checkbox meta fields "featured" and "hidden". I want to return a post which is has the "featured" field checked and the "hidden" field unchecked. My query is as follows:

$query_args = array(
  'posts_per_page' => '1',
  'orderby' => 'rand',
  'post_type' => 'nc_property',
  'meta_query' => array(
    array(
      'key' => 'nc_featured',
      'value' => 'on',
      'compare' => '='
    ),
    array(
      'key' => 'nc_hidden',
      'value' => 'on',
      'compare' => '!='
    )
  )
);

The query returns a random featured property if I remove the second array so the problem lies with my nc_hidden meta query but I'm not seeing it.

What's the correct way to check for an unchecked meta value?

Cheers.

3
  • 2
    does nc_hidden exist if it's not checked?
    – Milo
    Sep 25, 2014 at 16:31
  • ...I'm an idiot. I've swapped the nc_hidden property from a checkbox to a select. Everything now works. Thanks for the pointer :)
    – Jazibobs
    Sep 25, 2014 at 16:39
  • @Jazibobs What's the value if nc_hidden is checked / unchecked? On / Off or do you delete the meta whenever there is no value checked?
    – Howdy_McGee
    Sep 25, 2014 at 16:41

1 Answer 1

0

The problem was that the nc_hidden met property did not exist if it was not checked so there was essentially no value to query against.

I swapped nc_hidden from a checkbox to a select and updated my query as required. The working query is now as follows:

$query_args = array(
  'posts_per_page' => '1',
  'orderby' => 'rand',
  'post_type' => 'nc_property',
  'meta_query' => array(
    array(
      'key' => 'nc_featured',
      'value' => 'on',
      'compare' => '='
    ),
    array(
      'key' => 'nc_hidden',
      'value' => 'Visible',
      'compare' => '='
    )
  )
);

Thanks @Milo for pointing me in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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