【问题标题】:Showing posts between a certain date range显示特定日期范围内的帖子
【发布时间】:2011-08-12 18:04:39
【问题描述】:

尝试显示特定日期范围的自定义帖子类型。我只想显示某个月内的帖子。我知道我需要连接到 posts_where 过滤器,但我不知道如何将参数传递给这个函数,因为我需要传递日期范围。

我已经看到很多关于如何更改 WHERE 子句以获取日期范围的示例,但仅限于静态时。我需要执行以下操作:

add_filter('posts_where', 'my_custom_where', '', '04/2011'); //pass my date to the filter

function my_custom_where( $where = '' ) {

    //figure range  
    $range = array(
        'start' => $date . '-1',
        'end' => $date . '-' . cal_days_in_month(CAL_GREGORIAN, date('m', $date), date('Y', $date))
    );

    $where .= " AND post_date ....."; //build where with date range

    return $where;

}

希望这是有道理的。任何帮助将不胜感激。

【问题讨论】:

    标签: wordpress arguments archive custom-post-type add-filter


    【解决方案1】:

    如果你使用全局变量,你可以让它动态化。(不理想,但是嘿,我还没有找到更清洁的方法......)

    首先为日期定义一个全局变量

    $GLOBALS['start_date'] = '2011-07-31';
    

    然后添加您的过滤器

    add_filter( 'posts_where', 'filter_where' );
    
     function filter_where( $date, $where = '' ) {
        // posts later than dynamic date
        $where .= " AND post_date >= '" . date('Y-m-d H:i:s', strtotime($GLOBALS['start_date'])) . "'";
        return $where;
    }
    

    如果您只想为单个查询运行过滤器,请删除过滤器。

    【讨论】:

      【解决方案2】:

      这应该可以在过去 30 天内抓取帖子。但是请注意,放置在您的 functions.php 文件或插件中的此代码将在任何地方过滤您的帖子。如果您只希望它在某些页面上过滤,请将其包装在条件标签中,或者在模板页面上使用它:

      <?php
        function filter_where($where = '') {
          // Posts in the last 30 days
          $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
          return $where;
        }
      add_filter('posts_where', 'filter_where');
      query_posts($query_string);
      ?>
      

      我直接从http://wordpress.org/support/topic/show-the-posts-published-before-a-specific-date?replies=2#post-1066144 窃取了此代码,那里对此问题进行了更广泛的讨论,如果这不能完全满足您的要求,还有更多示例。

      【讨论】:

      • 是的,我看过这段代码。我不想显示过去 30 天的帖子。我正在尝试显示 30 天的帖子,这是动态的,由用户从下拉框中选择。与帖子存档非常相似,但用于自定义显示。所以我需要将此动态日期范围传递给过滤器。
      【解决方案3】:
      <?php
      // Show post from a theme option where posts_month is the month 1-12 and posts_year is the year (4 dig)
      
      $month = get_option( 'posts_month' );
      $year = get_option( 'posts_year' );
      
      $query = new WP_Query( 'year=' . $year . '&monthnum=' . $month );
      

      【讨论】:

        【解决方案4】:

        如果您不想做任何编码工作,那么可以借助 WordPress Posts listing plugin 的帮助。借助此功能,您可以在特定日期范围内显示帖子。

        只需提供开始和结束日期。您可以显示今天、本周、上周、本月和上个月的帖子。如果预定义选项不适合您,您可以显示最近 N 天发布的帖子

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-24
          • 2014-10-09
          相关资源
          最近更新 更多