2012-05-28 52 views
1

我正在尝试编写一个WP_Query,我只打给2012年3月之后发布的帖子。我可以成功地调用刚刚在2012年3月发布的帖子,但努力工作'从2012年3月起'。在Wordpress中某个日期后发布的查询帖子

$current_year = date('2012'); 
    $current_month = date('>3'); // This doesn't work 
    $current_month = date('3'); // This DOES work 

    $custom_query = new WP_Query("year=$current_year&monthnum=$current_month&order=ASC&posts_per_page=-1"); 

我是否缺少一些简单的东西,还是这样会变得更加复杂?

回答

8

http://codex.wordpress.org/Class_Reference/WP_Query中的“时间参数”部分有关于日期范围的说明。使用相同的技术:

$query_string = "order=ASC&posts_per_page=-1"; 

// Create a new filtering function that will add our where clause to the query 
function filter_where($where = '') { 
    $where .= " AND post_date >= '2012-03-01'"; 
    return $where; 
} 

add_filter('posts_where', 'filter_where'); 
$custom_query = new WP_Query($query_string); 
remove_filter('posts_where', 'filter_where'); 
+0

好极了,这完美地工作 - 谢谢! – SparrwHawk

6

由于WordPress版本3.7,还有的WP_Query说法date_query这完全适用于这种类型的查询。

As you can see in the Codex,您可以使用after参数指定日期查询。 after可以是strtotime()兼容的字符串,也可以是“year”,“month”,“day”值的数组。

对于你的榜样,像下面应该工作:

$args = array(
    'posts_per_page' => -1, 
    'date_query'  => array(
     'after' => array(
      'year' => 2012, 
      'month' => 3, 
      'day' => 1, 
     ), 
    ), 
); 
$custom_query = new WP_Query($args); 

或者用的strtotime() - 字符串:

$args = array(
    'posts_per_page' => -1, 
    'date_query'  => array('after' => '2012-03-01'), 
); 
$custom_query = new WP_Query($args); 
相关问题