Sort meta_query with boolean custom field

Viewed 729

I've been looking for hours to allow sticky post on archive page with a boolean field.

Everything works fine if my field is not boolean (date, number >= 2 or anything) else but I can't do anything with a Boolean field.

Here is my code :

$query->set( 'meta_query', array(
    'relation' => 'OR',
    array(
        'key' => 'cat_sticky_enabled',
        'compare' => 'EXISTS',
    ),
    array(
        'key' => 'cat_sticky_enabled',
        'compare' => 'NOT EXISTS'
    )
) );

$query->set( 'orderby', 'meta_value date' );
$query->set( 'order', 'DESC' );

In the case of a Boolean :

  • If I just call 'cat_sticky_enabled' which exists, I have a good result (all the checked posts).
  • If I just call 'cat_sticky_enabled' which not exists, I have a good result (all the unchecked posts).
  • If I call both, I have all my posts but I can't order them properly (tried whith meta_value and meta_value_num) :/

Thank you in advance for your answers. I'm missing something but I can't find it :/

Edit : excuse me, my code was 'OR', not 'AND'

1 Answers

I finally solved my problem :)

If it can help someone :

$query->set( 'meta_query', array(
    'relation' => 'OR',
    'field_order' => array(
        'key' => 'category_sticky_post_enabled',
        'compare'   => 'EXISTS',
        ),
    'field_order_withnulls' => array(
        'key' => 'category_sticky_post_enabled',
        'compare' => 'NOT EXISTS',
        )
    )
);

$query->set( 'orderby', 'field_order_withnulls post_date' );
$query->set( 'order', 'DESC' );
Related