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条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路