显示特定日期范围之间的帖子

Chr*_*ris 4 wordpress arguments archive add-filter custom-post-type

尝试显示特定日期范围的自定义帖子类型.我想仅在某个月内展示帖子.我知道我需要挂钩到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;

}
Run Code Online (Sandbox Code Playgroud)

希望有道理.任何帮助,将不胜感激.

小智 7

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

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

$GLOBALS['start_date'] = '2011-07-31';
Run Code Online (Sandbox Code Playgroud)

然后添加你的过滤器

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;
}
Run Code Online (Sandbox Code Playgroud)

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