wp_query sorting – one specific meta_key value at last and then sort by create date

I’m having a custom post type “products” of which I need to show a list. The products are sorted by meta value into different kinds of product type. I need to set one specific product type “tools” at the bottom of the list. But it also has to be sorted by create date. So all other product types sorted by create date and then the product type “tools” – also sorted by create date. Is this possible within one wp_query?

How are the arguments for the wp_query?

Answer

If you’re using WordPress 4.2 or newer then you can do the following:

$args = array( 
    'post_type'       => 'products',
    'posts_per_page'  => 10,
    'meta_query'      => array(
        'relation'    => 'AND',
        'tools_clause' => array(
            'key'     => 'tools',
            'compare' => 'EXISTS',
        ),
        'create_date_clause' => array(
            'key'     => 'create_date',
            'compare' => 'EXISTS',
        ),
    ),
    'order_by' => array(
        'create_date_clause' => 'ASC',
        'tools_clause' => 'ASC',
    )
);

Take a look here:
Query improvements in WP 4.2: ‘orderby’ and ‘meta_query’

Attribution
Source : Link , Question Author : HHGK , Answer Author : LUIS

Leave a Comment