2011-04-26 68 views
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; 

} 

希望是有道理的。任何幫助,將不勝感激。

回答

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

然後取出過濾器,如果你只是想運行單個查詢。

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,那裏就是一個大討論如果這個問題沒有得到你想要的結果,還有更多的例子。

+1

是的,我已經看過這段代碼。我不想顯示過去30天的帖子。我試圖顯示30天的帖子,該帖子是動態的,並且由用戶從下拉框中選擇。非常類似於文章歸檔,但用於自定義顯示。所以我需要將這個動態日期範圍傳遞給過濾器。 – Chris 2011-04-26 05:17:51

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); 
0

如果你不想做任何編碼工作,那麼很可能的幫助WordPress Posts listing plugin的這個。隨着幫助,您可以在一定時間範圍之間顯示的帖子。

只需提供開始日期和結束日期。您可以顯示今天,本週,上週,本月和上月的帖子。如果預定義選項不適合您,您可以顯示發佈在過去N天的帖子。

相關問題