0

I am using this query for my loop and it is working except when meta_value is empty. In this case it returns empty result. Instead I want to get all results when meta_value is empty.

Here is my code

$query = new WP_Query( array(
    'post_type'  => 'my_post_type',
    'meta_query' => array(
        array(
            'key'     => 'state',
            'value'   => 'Alabama',
        ),
        array(
            'key'     => 'country',
            'value'   => $region,
        ),
    ),
) );

I want to get all results in state Alabama when variable region will be empty. Any suggestion about this will be much appreciated.

1

If I understand your question correctly, you want to query for region field only if $region variable is not empty? If so, this should work and it will be much prettier code than the one you suggested:

$meta_query = array(
    array(
        'key'     => 'state',
        'value'   => 'Alabama',
    ),
);

if ( $region ) {
    $meta_query[] = array(
        'key'     => 'country',
        'value'   => $region,
    );
}

$query = new WP_Query( array(
    'post_type'  => 'my_post_type',
    'meta_query' => $meta_query
) );
  • Thank you so much for your answer and yes it is much prettier code and best way to achieve this. But i was able to get desired results with above mention code in my own answer last night. – wplearner Mar 22 '18 at 9:51
  • Your answer will get a little bit different results. Your code will ignore posts without country meta_value at all. My code will still return such posts. – Krzysiek Dróżdż Mar 22 '18 at 9:54
  • Okay i will test my posts again and then in this case will implement your code. Thank you so much for your suggestion. – wplearner Mar 22 '18 at 9:57
0

This code is working for me

$query = new WP_Query( array(
    'post_type'  => 'my_post_type',
    'meta_query' => array(
        array(
             'key'     => 'state',
             'value'   => 'Alabama',
        ),
        array(
             'key'     => 'country',
             'value'   => $region,
             'compare' => $region ? "=" : "!=",
        ),
     ),
   ));

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.