Skip to main content

WordPress Orderby Query Parameters

I recently upgraded a large publisher site from an old 3.6.1 install to a 4.x version which allowed me to utilise the powerful orderby parameters in WordPress 4+.

Using the following code as an example it is a fairly trivial task to orderby both date and a custom field value named 'article_weight':

$args = array(
    'post_type' => 'post',
    'orderby' => array( 'article_weight' => 'ASC', 'date' => 'DESC' ),
    'meta_type' => 'NUMERIC',
    'meta_key'  => 'article_weight',
);
$query = new WP_Query( $args );

The above code allows for posts to be ordered by article_weight first and date second. This allows for posts of varying 'stickiness' to be displayed within post listings such as category or tag archive pages.

If you want to apply a default query to all queries that don't feature a custom 'order' query parameter then try this:

//custom query data
function weight_meta_query( $query )
{
    //ignore feeds
    if($query->query['feed']){
        return;
    }
    //ignore attachments
    if($query->query['attachment']){
        return;
    }
    //ignore admin
    if ( !is_admin() ) {
        //if custom ordering has been set anywhere in a query then return the original query
        if(isset($query->query['order'])){
            $order = $query->query['order'];
            return $query;
        }
        //don't set query on pages, date archives or search pages.
        if ( !is_page() && !is_date() && !is_search()) {
            $query->set('meta_key', 'article_weight');
            $query->set('meta_type', 'NUMERIC');
            $query->set('orderby', array( 'meta_value' => 'ASC' ));
        }
    }
}
add_action( 'pre_get_posts', 'weight_meta_query' );

Using the above code will mean that you don't have to write custom queries for all loops in your site which is a real time saver!