douyu1656 2013-06-17 19:38
浏览 36
已采纳

如何在Wordpress外循环中对自定义字段日期进行排序

I am trying to sort pages by a custom field which has the 'yyyy/mm/dd' format. The problem I have is no matter what I have tried I keep getting the list back in alphabetical order by title.

Is there anyway to do a query outside the loop and have the pages returned in the sorted order?

$args = array(
    'parent' => 462, 
    'child_of' => 462,
    'sort_column' => 'Date',
    'post_status' => 'publish',
    'sort_order' => 'ASC'
); 
$pageposts = get_pages($args);

I did try with this as well, but I still cannot seem to get it to work.

$args = array(
    'meta_key' => 'Date',
    'orderby' => 'meta_value_num',
    'parent' => 462, 
    'child_of' => 462,
    'post_status' => 'publish',
    'order' => 'ASC'
); 
$pageposts = get_pages($args);

I did try with meta_value as well as meta_value_num. I am completely lost and am not really understanding why I cannot figure this out. Thank you all in advance for any help. I know this may be remedial to most, so I really appreciate it.

  • 写回答

2条回答 默认 最新

  • dsgm5631 2013-06-17 21:33
    关注

    You need to use your custom query because wordpress get_pages,get_posts will sort the meta_value as string so if you use the above functions your field will be treated as the string not the date here is the example you can add further your conditions in the query

    global $wpdb;
    $query = "
            SELECT wp.*
            FROM $wpdb->posts wp, $wpdb->postmeta wm
            WHERE wp.ID = wm.post_id
            AND wm.meta_key = 'Date'
            AND wp.post_status = 'publish'
            AND wp.post_type = 'page'
            AND wp.post_parent = '462'
            ORDER BY STR_TO_DATE(wm.meta_value, '%m/%d/%Y') ASC
            ";
    
        $pages = $wpdb->get_results($query, OBJECT);
    

    Note*The date must be inputted in the American format i.e 21/02/2009 for it to work*

    Hope it makes sense

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部