获取在 wordpress 中特定日期之间发布的帖子 [英] Get posts published between specific dates in wordpress

查看:28
本文介绍了获取在 wordpress 中特定日期之间发布的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个小部件,该小部件将显示两个日期之间发布的帖子,例如 1 月 15 日和 3 月 15 日,但我不知道该怎么做.

I'm working a on a widget that will display posts published between two dates, for example Jan 15 and March 15, but I don't know how do it.

我看到了一些提到 query_posts() 的解决方案,但我认为这不是一个好的解决方案.所以我愿意接受任何关于如何做到这一点的建议.

I saw a few solutions that mention query_posts() but I don't think that's a good solution. So I'm open to any suggestions how to do this.

目前我正在考虑使用 pre_get_posts、WP_Query 或 get_posts 并尝试使用以下代码行:

At the moment I'm thinking using pre_get_posts, WP_Query, or get_posts and I tried with this line of code:

function my_home_category( $query ) 
{
    if ( $query->is_home() && $query->is_main_query() )
    {
        $query->set( 'day', '15');
    }
}
add_action( 'pre_get_posts', 'my_home_category' );

但这会返回任何一个月的 15 日发布的所有帖子.我知道我可以设置如下:

But this returns all the posts published on 15th of any month. I know I can set something like:

 $query->set( 'monthnum', '1');

并在 1 月 15 日发布帖子,但我希望在 1 月 15 日至 3 月 15 日之间发布所有帖子,但我不知道如何实现.

and get posts published on 15th January, but I want to get all posts published between 15th Jan - 15th March, and I don't know how to achieve that.

不必使用 pre_get_posts,它可以是 get_posts 或 WP_Query,我只是在寻找一种简单的方法.

It doesn't have to use pre_get_posts, it could be get_posts or WP_Query, I'm just looking for a simple way to do it.

推荐答案

WP_Query 提供了一个 date_query 参数,允许您设置一个范围与之前和之后.

WP_Query offers a date_query parameter, allowing you to set a range with before and after.

https://developer.wordpress.org/reference/classes/wp_query/#date-参数

$args = array(
    'date_query' => array(
        array(
            'after'     => 'January 1st, 2015',
            'before'    => 'December 31st, 2015',
            'inclusive' => true,
        ),
    ),
);
$query = new WP_Query( $args );

这篇关于获取在 wordpress 中特定日期之间发布的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆