0

I'm trying to order product post type with custom meta field for an expiration date.

I want to show all the expiring products (first being the expiring soon ones). After them, I want to show all the rest of the products that have an empty or missing expiration date after them in alphabetical order.

I have this in pre_get_post hook:

$meta_query = array(
    'relation' => 'OR',         
        array(
            'key' => 'expiring_date',
            'value' => date('Ymd'),
            'compare' => '>',
            'type' => 'DATE'
        ),
        array(
            'key' => 'expiring_date',
            'compare' => 'NOT EXISTS'
        ),
        array(
            'key' => 'expiring_date',
            'value' => ''
        ),              
    );

    $query->set( 'meta_query', $meta_query );
    $query->set('meta_key', 'expiring_date');
    $query->set('orderby', array( 
        'meta_value_num' => 'ASC', 
        'title' => 'ASC' 
    ));

The problem is that WordPress always shows the expiring products after the products with missing date. Changing the meta_value_num to DESC puts them at the before them as it should be but they are ordered from latest expiration to soonest.

Any help?

1

You should be able to name and sort your meta query clauses like this:

$meta_query = array(
    'relation' => 'OR',         
        'foo' => array(
            'key' => 'expiring_date',
            'value' => date('Ymd'),
            'compare' => '>',
            'type' => 'DATE'
        ),
        'bar' => array(
            'key' => 'expiring_date',
            'compare' => 'NOT EXISTS'
        ),
        'baz' => array(
            'key' => 'expiring_date',
            'value' => ''
        ),              
    );

    $query->set( 'meta_query', $meta_query );
    $query->set('meta_key', 'expiring_date');
    $query->set('orderby', array( 
        'foo' => 'ASC',
        'bar' => 'DESC',
        'baz' => 'ASC',
        'title' => 'DESC' 
    ));

More information can be found in this introduction post.

  • Yeah, I tried this it still loads them after the products without expiration date :( – Ziik Feb 8 '18 at 15:39

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.