query_posts with a custom post type, a meta_query and sorting by post date?

I’ve searched the archives and found questions similar to what I need, but haven’t found exactly what I want.

I’ve got a bunch of products that are sorted by a meta_key of country, and I’d like to be able to allow the user to sort either by the post title (product name) or the post date (how long the product’s been in the database. What I’m experiencing is that if I select the country to display, that works properly, but will only order by post title. If I select “all countries”, which does not add a meta_query, sorting by date desc works.

Here’s the code I’ve got:

$meta_queries = array();

if ( $_REQUEST['country'] ) {
    $meta_queries[] = array(
        'key' => 'country',
        'value' => $_REQUEST['country'],
        'compare' => '=',
    );
}

$sort_by = 'title';
$sort_order="ASC";
if ( $_REQUEST['sort_by'] == 'new_products' ) {
    $sort_by = 'date';
    $sort_order="DESC";
}


query_posts(array(
    'post_type' => 'currency', // custom post type
    'paged' => 1,
    'orderby' => $sort_by,
    'order' => $sort_order,
    'meta_query' => $meta_queries,
));

TL;DR, is there a way to have a meta_query AND sort by the post date?

0

Leave a Comment