2012-05-28 54 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); 
相關問題