简体   繁体   English

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

[英]How to sort custom field date in Wordpress outside loop

I am trying to sort pages by a custom field which has the 'yyyy/mm/dd' format. 我正在尝试按具有'yyyy / mm / dd'格式的自定义字段对页面进行排序。 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. 我确实尝试过meta_value以及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. 我知道这可能是大多数情况下的补救措施,所以我非常感谢。

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 您需要使用自定义查询,因为wordpress get_pages,get_posts会将meta_value排序为字符串,因此,如果您使用上述函数,那么您的字段将被视为字符串而不是date这里是示例,您可以在查询中进一步添加条件

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 ie 21/02/2009 for it to work * 注意* 日期必须以美国格式输入,即2009年2月21日,日期才能生效 *

Hope it makes sense 希望有道理

只需使用'sort_column'=>'post_date',

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM