【问题标题】:Order by custom field date按自定义字段日期排序
【发布时间】:2016-06-23 01:39:24
【问题描述】:

我正在使用它来列出所有帖子标题...

<?php
$args = array(
    'posts_per_page'    => -1,
    'post_type'         => 'post',
    'post_status'       => 'publish',
    'orderby'           => 'title',
    'order'             => 'ASC'
);

query_posts($args);
if (have_posts()) :
    while (have_posts()) :
    the_post(); ?>
<p>
    <?php the_title(); ?>
</p>
<?php endwhile;
    endif;
    wp_reset_query();
?>

...效果很好。

我的每个帖子还有一个名为 start_date 的自定义字段。所有这些开始日期都以 DD-MM-YYYY 格式输入(例如:10-03-2016)。

我需要能够做的(如果这甚至可以做到的话,我不会)是通过start_date(而不是title)订购。

为了进一步说明,如果有 3 个帖子的开始日期是这样的......

帖子 1:2016 年 1 月 11 日

帖子 2:2016 年 3 月 1 日

帖子 3:2016 年 7 月 12 日

...帖子将按...的顺序显示

发布 2

发布 3

发布 1

...因为这是正确的日期顺序。

我希望这是有道理的。

干杯。

【问题讨论】:

    标签: php wordpress date custom-fields


    【解决方案1】:

    在 wordpress WP_Query 类中,接受 args 为后期过滤提供了更多帮助。 您可以在官方站点文档中查看提供自定义元字段在查询参数中接受的 order 和 orderby。

    https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

    在这种情况下我有两种方法处理。

    1. 开始日期中的日期格式不正确 mysql 日期格式(YYYY-MM-DD)。如果您的日期格式将与 mysql 格式相同,那么您只需更改查询参数,例如:
    $args = 数组( 'posts_per_page' => -1, 'post_type' => '发布', 'meta_key' => 'start_date', 'post_status' => '发布', 'orderby' => 'meta_value', 'meta_type' => '日期', '订单' => 'ASC' );
    1. 如果您不想更改每个帖子的日期格式,或者您有很多帖子很难更改每个帖子的日期格式,那么您可以添加过滤器以覆盖订单参数。

    完整代码

    <?php
        $args = array(
            'posts_per_page'    => -1,
            'post_type'         => 'post',
            'post_status'       => 'publish',
            'meta_key'          => 'start_date',
            'orderby'           => 'title',
            'order'             => 'ASC'
        );
    add_filter( 'posts_orderby', function($orderby){
     return 'STR_TO_DATE( wp_postmeta.meta_value, "%d-%m-%Y") ASC';
    });
    query_posts($args);
    if (have_posts()) :
        while (have_posts()) :
        the_post(); ?>
    <p>
        <?php the_title(); ?>
    </p>
    <?php endwhile;
        endif;
        wp_reset_query();
    ?>
    

    希望这对你有帮助抱歉英语不好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 2018-04-25
      • 2016-06-10
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多