4

尝试显示特定日期范围的自定义帖子类型。我只想显示某个月内的帖子。我知道我需要连接到 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;

}

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

4

4 回答 4

7

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

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

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

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

于 2011-09-07T13:30:29.893 回答
3

这应该可以在过去 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 ,其中有更大的讨论这个问题,如果这没有得到你想要的,还有更多的例子。

于 2011-04-26T05:03:08.883 回答
1
<?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 );
于 2011-04-26T09:52:36.827 回答
0

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

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

于 2016-08-11T09:15:28.030 回答