WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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';

    '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?

share|improve this question
From your code I cannot see why this is not working. You can sort by date when using a meta_query. Only thing I could think is that when you send country, sort_by is not being sent too so it is falling back to ordering by title – Brady Mar 26 '12 at 8:11
I do suggest you validate the $_REQUEST['country'] – janw Mar 26 '12 at 8:55
Brady: That's what I thought, but I echo'd out $sort_by and it does have the correct value, and if you set it to "All Countries" without changing the sort order, it will start sorting automagically. JanW: Good point, I'll add that. – Rob Williams Mar 26 '12 at 12:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.