How do I query posts and use the 'orderby' attribute to order posts in loop according to date 'meta_value'?

拥有回忆 提交于 2019-11-29 18:03:09
Raunak Gupta

You can spicify the datatype in orderby key like meta_value_* possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.

Try this,

$futureProd = array(
    'post_type' => 'productions',
    'posts_per_page' => -1,
    'meta_key' => 'ending_date',
    'orderby' => 'meta_value_date',
    'order' => 'ASC',
);

$slider_posts = new WP_Query($futureProd);

Please Note: for above code to work you need to have date in YYYY-MM-DD format if you have date in different format then you have to create your custom filter function hook in to posts_orderby filter with STR_TO_DATE MySQL function.


For date format YYYYMMDD

Add this in your active theme function.php file of your active child theme (or theme). Or also in any plugin php files.

function text_domain_posts_orderby($orderby, $query) {
    //Only for custom orderby key
    if ($query->get('orderby') != 'yyyymmdd_date_format')
        return $orderby;
    if (!( $order = $query->get('order') ))
        $order = 'ASC';
    global $wpdb;
    $fieldName = $wpdb->postmeta . '.meta_value';
    return "STR_TO_DATE(" . $fieldName . ", '%Y%m%d') " . $order;
}

add_filter('posts_orderby', 'text_domain_posts_orderby', 10, 2);

So now your WP_Query argument should look like this:

$futureProd = array(
    'post_type' => 'productions',
    'posts_per_page' => -1,
    'meta_key' => 'ending_date',
    'orderby' => 'yyyymmdd_date_format', //added custom orderby key
    'order' => 'ASC',
);

The code is tested and fully functional.

Reference:

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!