0

I have an age filter, where it checks two custom fields, min_age and max_age, max_age is optional so it can be empty.

These don't seem to work together:

    array(
      'key'     => 'max_age',
      'value'   => $max_age,
      'type' => 'numeric',
      'compare' => '<=',
    ),
    array(
      'key'     => 'max_age',
      'value'   => '',
      'compare' => '!=',
    )

If I remove the top array (<= filter), it returns the correct results, only showing results with the correct min_age and results that have a max_age value. How can I make them work together because the != '' max_age filter is needed, otherwise the max_age <= filter doesn't work correctly because it ignores that filter if the max_age custom field is empty.

      $query->set( 'meta_query', array(
        'relation' => 'AND',
        array(
          'key'     => 'min_age',
          'value'   => $min_age,
          'type' => 'numeric',
          'compare' => '>=',
        ),
        array(
          'key'     => 'max_age',
          'value'   => $max_age,
          'type' => 'numeric',
          'compare' => '<=',
        ),
        array(
          'key'     => 'max_age',
          'value'   => '',
          'compare' => '!=',
        )
      ));

1 Answer 1

0

You can use isset to check if the values are set, and then pass them as arguments. Divide your query by 2 parts and use them as needed.

// Check if both are set 
if ( isset( $max_age ) && isset( $min_age ) ) {
    $meta_query = array(
        'relation' => 'AND',
        array(
          'key'     => 'min_age',
          'value'   => $min_age,
          'type' => 'numeric',
          'compare' => '>=',
        ),
        array(
          'key'     => 'max_age',
          'value'   => $max_age,
          'type' => 'numeric',
          'compare' => '<=',
        ),
        array(
          'key'     => 'max_age',
          'value'   => '',
          'compare' => '!=',
        )
    );
} else {
    $meta_query = array(
        array(
          'key'     => 'min_age',
          'value'   => $min_age,
          'type' => 'numeric',
          'compare' => '>=',
        )
    );
}
// Now set the query
$query->set( 'meta_query', $meta_query );

If both $min_age and $max_age are always set and you want to check if they are empty or not, you can use empty() instead of isset().

1
  • $min_age and $max_age are filters passed to this, this would not work as I need to check if the actual post has values for min_age and max_age custom fields. Commented Jul 22, 2017 at 14:26

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.