Search code examples
wordpresspodscms

Order of custom posts in custom Wordpress query not as expected


I have a custom Wordpress query which looks like this:

$args = array(
    'post_type' => 'publication',
    'post_status' => 'publish',
    'category_name' => 'my-category',
    'posts_per_page' => 20,
    'orderby' => 'publication_year',
    'order' => 'DESC',
    'paged' => $paged
);
$loop1 = new WP_Query($args);

I am querying a custom post type, wanting only the posts with a certain category. FWIW, I created the post type using PODS. The query works properly with one little exeption - the order clause:

The orderby field refers to a date field named "publication_year" which only shows the year values 2015, 2014, 2013 etc., but in the database contains full dates like "2013-01-18" and similar.

Now, the order which I get with the above query is 2013, 2014, 2015 - although order is DESC, for which I would expect the opposite. If I change it to ASC, I get 2015, 2014, 2013!

I don't understand that - I would expect ascending order to be 2013, 2014, 2015 etc. Where am I wrong?


Solution

  • publication_year is not a column in the wp_posts table. See the WordPress Database Description. If the orderby parameter is not valid, WordPress will fall back to the default sorting which is the post_date column.

    If it is a meta value you should use:

    $args = array(
        'post_type' => 'publication',
        'post_status' => 'publish',
        'category_name' => 'my-category',
        'posts_per_page' => 20,
        'orderby' => 'meta_value_num',
        'meta_key' => 'publication_year',
        'order' => 'DESC',
        'paged' => $paged
    );
    

    See the WordPress codex for more information.