douyu1656 2013-06-18 03: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-18 05: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条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog