Order by Date Custom Field

时间:2018-12-12 作者:David Barclay

我试图按开球顺序显示即将到来的足球比赛列表。我目前的代码以正确的顺序列出了日期,但帖子的顺序不正确。

<?php
$previews_new_loop = array(
    \'posts_per_page\' => -1,
    \'post_type\'      => \'football_match\',
    \'meta_key\'       => \'kick-off-date\',
    \'orderby\'        => \'meta_value\',
    \'order\'          => \'ASC\',
);

$wpquery = new WP_Query( $previews_new_loop );   
$posts = $wpquery->get_posts();
$ordered_posts = array();

foreach ( $posts as $post ) {
    $meta_value = get_post_meta( $post->ID, \'kick-off-date\', true );
    if ( !$meta_value ) {
        continue;
    }
    $date = date( \'ddmmyyyy\', strtotime( $meta_value ) );
    $ordered_posts[$date][] = $post;
}

foreach ( $ordered_posts as $post_date => $posts ) {
    foreach ( $posts as $post ):
    endforeach;
}

1 个回复
最合适的回答,由SO网友:anmari 整理而成

我将下面的代码(从您的代码开始)设置为一个短代码,效果很好。当我将方向“ASC”更改为“DESC”时,排序顺序也会更改,因此帖子的顺序是否正确并不“幸运”。它假定日期存储为yyyymmdd。请注意,必须删除该行:

$date = date(\'ddmmyyyy\', strtotime($meta_value)); 
如果日期已存储在ddmmyyyy。

function sort_by_date() {
        $previews_new_loop = array(
    \'posts_per_page\' => -1,
    \'post_type\' => \'article\', //\'football_match\',
    \'meta_key\' => \'kick-off-date\',
    \'orderby\' => \'meta_value\',
//  \'order\' => \'ASC\',);
\'order\' => \'DESC\',);

    $wpquery = new WP_Query($previews_new_loop);   
    $posts = $wpquery->get_posts();  
    $ordered_posts = array();
    foreach ($posts as $post) {
        $meta_value = get_post_meta($post->ID, \'kick-off-date\', true);
        if (!$meta_value) {
            continue;
        }
        //$date = date(\'ddmmyyyy\', strtotime($meta_value));
        $ordered_posts[$meta_value][] = $post;
    }
    $html = \'<pre>\'.print_r($ordered_posts, true).\'</pre>\';
    return $html;
}

add_shortcode(\'sort_by_date\',\'sort_by_date\');

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post