2014-09-05 13 views
0

我如何提供日期參數在這裏,以便我從上週獲得帖子。使用get_posts方法獲取上週的帖子

請注意,這是插件的一部分,只能在星期一運行。所以我想從上週一到昨天(週日下午11:59)獲得帖子。

我知道有方法通過使用WP_Query但因爲我不是在使用WP_Query並獲得意想不到的效果舒服,我想用這種get_posts方法

$posts_in_category = get_posts(array('category' => $category_id, 'post_status' => 'publish')); 

回答

1

堅持爲你正在嘗試做的,我d推薦使用WP_Query而不是get_posts()get_posts()在它可以提取的帖子範圍內的範圍非常有限,因爲您只能指定少量的搜索條件。 WP_Query(這是get_posts()使用的)允許您指定大量額外條件,包括日期參數。

參見:http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

這裏是WordPress的抄本,其獲取在上週的帖子變形例:

//WP_Query Arguments 
$args = array(
    'date_query' => array(
     array(
      'column' => 'post_date', 
      'after' => '1 week ago', 
     ) 
    ), 
    'posts_per_page' => -1 
); 

//Execute WP_Query (Results placed in $the_query) 
$the_query = new WP_Query($args); 

//The WordPress Loop 
if ($the_query->have_posts()) { //Check if there are any posts returned in $the_query 
    echo '<ul>'; 
    while ($the_query->have_posts()) { //Loop through posts returned in $the_query 
     $the_query->the_post(); 
     echo '<li>' . get_the_title() . '</li>'; 
    } 
    echo '</ul>'; 
} else { //If no posts found 
    echo "No Posts Found"; 
} 

//Reset WordPress Post Data 
wp_reset_postdata(); 

從WordPress抄本該流程圖演示瞭如何WP_Queryget_posts()工作:

enter image description here

相關法典條目:

WP_Query:http://codex.wordpress.org/Class_Reference/WP_Query

+0

我嘗試使用WP_Query,但它不是取結果 – 2014-09-05 14:07:23

+0

針對日期參數你說你已經嘗試過WP_Query,或者我的代碼不工作? – Mastrianni 2014-09-05 14:11:00

+0

@mastianni不,我說我已經嘗試WP_Query,但是看到你的代碼後,我發現我的錯誤:)感謝很多 – 2014-09-05 14:23:18

1

可以achievethis不循環,使用許多黑客之一WP。 首先創建一個名爲filter_where()的函數,它包含一個SQL「WHERE」條件。然後,在啓動循環之前,將filter_where()函數掛接到WordPress的post_where()函數中。

因此,filter_where()函數中包含的「WHERE」子句將添加到post_where()函數中包含的SQL查詢的末尾,這意味着該循環將返回僅在兩個在filter_where()函數中指定的日期。

,用今天的日期和上週的日期,自動生成 EXAMLPE:

<?php 

$date_current = date("Y-m-d");// current date 
$date_old = strtotime(date("Y-m-d", strtotime($date)) . " -1 week"); 

    function filter_where($where = '') { 
     $where .= " AND post_date >= $date_old AND post_date <= $date_current "; 
    return $where; 
    } 
add_filter('posts_where', 'filter_where'); 
query_posts($query_string); 
while (have_posts()) : 
     the_post(); 
     the_content(); 
endwhile; 

?> 
+0

爲什麼人們不鼓勵query_posts呢?它會返回與get_posts相同的posts數組嗎? – 2014-09-05 14:26:14

+1

'query_posts'不是由WordPress codex推薦的,還有更好的內置方法來獲取帖子。你可以閱讀爲什麼不建議在本頁的第一段:http://codex.wordpress.org/Template_Tags/query_posts – Mastrianni 2014-09-05 14:32:22

+1

WordPress循環功能非常強大,以及query_posts()函數,它允許您指定一些循環檢索帖子的參數。雖然,沒有內置函數或參數可以在兩個日期之間獲取帖子。 – user3042036 2014-09-05 14:41:48

0

您也可以使用這種方式,這是更安全還是第一位的,但只使用準備語句,因爲安全風險。

<?php 
$current_day = date('j'); 
$last_year = date('Y')-1; 
query_posts('day='.$current_day.'&year='.$last_year); 
if (have_posts()): 
    while (have_posts()) : the_post(); 
     the_title(); 
     the_excerpt(); 
    endwhile; 
endif; 
?> 

參見:codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

得到你想要顯示的結果