get_posts 不超过 X 天 - Wordpress

Posted

技术标签:

【中文标题】get_posts 不超过 X 天 - Wordpress【英文标题】:get_posts no older than X days - Wordpress 【发布时间】:2013-06-04 08:47:44 【问题描述】:

在我的 Wordpress 网站中,我使用这个 get_posts 代码:

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

如何过滤它以使帖子不超过 10 天?所以它应该只列出过去 10 天的帖子。

【问题讨论】:

【参考方案1】:

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

所以它看起来像:

$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);

【讨论】:

【参考方案2】:

The exemple from the doc 应该可以正常工作。 get_posts() 在幕后使用WP_Query() 发出实际请求。对于您的情况,修改后的示例应如下所示:

// 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' );

【讨论】:

我无法理解如何将此解决方案集成到我当前的代码中。我已经用我的完整代码更新了我的问题,您能否看一下并演示您的解决方案如何与我的代码一起使用?如果它确实有效,我肯定会接受这个答案是正确的。 @HenrikPetterson:我的解决方案与您的完整代码几乎相同。你要做的是 1 - 定义一个自定义过滤器,它可以满足你的需求(我的答案中的“filter_where()”函数,限制为过去十天), 2 - 从现在开始使用 add_filter 将过滤器添加到所有查询中, 3 - 运行查询,get_post() 将调用 wp_query() 它将应用您的过滤器,4 - 使用 remove_filter() 删除过滤器,因此它不适用于将/可能跟随的其他查询。唯一的变化是将 $query 重命名为 $posts。 您知道我在发布该评论时理解了解决方案。很好的答案。接受。

以上是关于get_posts 不超过 X 天 - Wordpress的主要内容,如果未能解决你的问题,请参考以下文章

超过N天没有访问的文件。

日期天数不应超过 31 天

在 X 天 WooCommerce 订单后发送自定义电子邮件 [重复]

Python(五十四)cookie与session

php get_posts

php get_posts