简体   繁体   English

get_posts 不超过 X 天 - Wordpress

[英]get_posts no older than X days - Wordpress

In my Wordpress site, I use this get_posts code:在我的 Wordpress 站点中,我使用了这个get_posts代码:

get_posts(
        array (
            'numberposts' => 5,
            'orderby'=>'comment_count',
            'order'=>'DESC',
            'post_type'   => array ( 'post' )
        )

How do I filter it so that the posts are not older than 10 days?如何过滤它以使帖子不超过 10 天? So it should only list posts from the past 10 days.所以它应该只列出过去 10 天的帖子。

As of 3.7 you can use date_query https://developer.wordpress.org/reference/classes/wp_query/#date-parameters从 3.7 开始,您可以使用 date_query https://developer.wordpress.org/reference/classes/wp_query/#date-parameters

So it would look like:所以它看起来像:

$args = array(
    'posts_per_page' => 5,
    'post_type' => 'post',
    'orderby' => 'comment_count',
    'order' => 'DESC',
    'date_query' => array(
        'after' => date('Y-m-d', strtotime('-10 days')) 
    )
); 
$posts = get_posts($args);

The exemple from the doc should work just fine. 文档中的示例应该可以正常工作。 get_posts() uses WP_Query() behind the scene to make the actual request. get_posts()在幕后使用WP_Query()来发出实际请求。 For your case the modified example should look something like this:对于您的情况,修改后的示例应如下所示:

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
    // posts in the last 30 days
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-10 days')) . "'";
    return $where;
}

add_filter( 'posts_where', 'filter_where' );
$query = get_posts(array (
            'numberposts' => 5,
            'orderby'=>'comment_count',
            'order'=>'DESC',
            'post_type'   => array ( 'post' )
         ));
remove_filter( 'posts_where', 'filter_where' );

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

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