Skip to content

Instantly share code, notes, and snippets.

@stevenspads
Created July 9, 2016 05:34
Show Gist options
  • Save stevenspads/f31e3fb0c6a8fb91fa3b9086f43e90ff to your computer and use it in GitHub Desktop.
Save stevenspads/f31e3fb0c6a8fb91fa3b9086f43e90ff to your computer and use it in GitHub Desktop.
WordPress Sorting WP_QUERY results by multiple meta keys
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'product',
'posts_per_page' => POSTS_PER_PAGE,
'paged' => $paged,
'meta_query' => array(
'relation' => 'AND',
'price' => array(
'key' => 'price',
'type' => 'NUMERIC',
'compare' => 'EXISTS',
),
'rating' => array(
'key' => 'rating',
'type' => 'NUMERIC',
'compare' => 'EXISTS',
),
)
);
$sort = isset( $_GET['sort'] ) ? esc_attr( $_GET['sort'] ) : 'most-recent';
switch( $sort )
{
case 'most-recent':
$args['orderby'] = array(
'date' => 'DESC',
'rating' => 'DESC'
);
break;
case 'price-high':
$args['orderby'] = array(
'price' => 'DESC',
'rating' => 'DESC'
);
break;
case 'price-low':
$args['orderby'] = array(
'price' => 'ASC',
'rating' => 'DESC'
);
break;
case 'rating-high':
$args['orderby'] = array(
'rating' => 'DESC',
'price' => 'ASC'
);
break;
case 'rating-low':
$args['orderby'] = array(
'rating' => 'ASC',
'price' => 'ASC'
);
break;
}
$results = new WP_Query( $args );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment