Skip to content

Instantly share code, notes, and snippets.

@ajithrn
Created August 2, 2015 18:07
Show Gist options
  • Save ajithrn/90bf5044454c96e7645a to your computer and use it in GitHub Desktop.
Save ajithrn/90bf5044454c96e7645a to your computer and use it in GitHub Desktop.
WP: Order by multiple meta keys in WP Query
<?php
/**
* This will allow to sort/filter according to different meta key values
* ref: https://mathieuhays.co.uk/order-by-multiple-post-meta-in-wp-query/
*
*/
$args = array(
'post_type' => 'my_post_type',
'posts_per_page' => 10,
'meta_query' => array(
'filter_key' => array(
'key' => 'filter_meta',
'value' => $custom_value,
'compare' => 'LIKE'
),
'custom_key' => array(
'key' => 'custom_meta',
'compare' => 'EXISTS'
),
'other_key' => array(
'key' => 'other_meta',
'compare' => 'EXISTS'
)
),
'orderby' => array(
'custom_key' => 'DESC',
'other_key' => 'ASC',
'title' => 'ASC'
)
);
$my_custom_query = new WP_Query( $args );
if( $my_custom_query->have_posts() ){
while( $my_custom_query->have_posts() ){
$my_custom_query->the_post();
// Do stuff
the_title();
}
}
wp_reset_postdata();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment