【问题标题】:get_posts no older than X days - Wordpressget_posts 不超过 X 天 - 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 天的帖子。

【问题讨论】:

    标签: php arrays wordpress posts


    【解决方案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。
      • 您知道我在发布该评论时理解了解决方案。很好的答案。接受。
      猜你喜欢
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多