2013-12-17 63 views
1

我已經編寫了這個循環來引入在過去30天內獲得最多視圖的帖子(將視圖計數作爲自定義元鍵記錄到數據庫)。wp_query by meta key

雖然我多想了一會兒,但我並不確定自己是否以'正確'的方式,或者至少是最合乎邏輯的方式進行討論。

<?php 

       // Create a new filtering function that will add our where clause to the query 
       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'); 

        $popularpost = new WP_Query(array( 
       'posts_per_page' => 33, 
       'meta_key' => 'wpb_post_views_count', 
       'orderby' => 'meta_value_num', 
       'order' => 'DESC' 

       )); 


       remove_filter('posts_where', 'filter_where'); ?> 


       <?php if ($popularpost->have_posts()) : ?> 



       <?php while ($popularpost->have_posts()) : $popularpost->the_post(); ?> 

      <article <?php post_class('item-post block'); ?> id="post-<?php the_ID(); ?>"> 
         <?php the_title(); ?> 
      </article> <!-- end div post --> 


       <?php endwhile; wp_reset_query(); ?> 

       <?php endif; ?> 

所以,你可以看到我在限制日期範圍爲30天,由meta_value_num排序的職位和獲得33個職位。

因此,邏輯上發生了什麼是在過去30天內發佈的任何帖子將按照他們擁有多少視圖的順序顯示在這裏。 我想到的是,當我創建了一個頁面來拉動過去7天裏瀏覽量最高的33篇文章時,它們是一樣的。明顯。

所以我認爲我想要做的是通過他們在過去30天/ 7天內有多少次視圖獲取帖子,而不是在這些日期範圍內發佈的帖子。

我在想什麼?如果是這樣,你能告訴我怎麼去做嗎?

+0

其實,你想30觀看次數最多的職位,這很好,但日期範圍內或沒有任何日期範圍很混亂? 如果沒有日期範圍,您可以隨時獲得最高觀看次數的信息。 – sven

回答

0
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'"; 

的strtotime('30天)=現在+ 30天

+0

你能解釋你的答案嗎? – andy

+0

你的[function filter_where]使用錯誤的日期計算。它假設是[strtotime(' - 30天')],如果你正在尋找過去30天的職位。 [strtotime('30 days')]意味着未來30天。 – Zac

+0

啊,是的,它實際上是-30,我寫這篇文章時我錯誤地粘貼了它。但是問題仍然是一樣的,它仍然會檢索過去30天內的帖子,而不一定是那些在過去30天內獲得最多觀看次數的帖子。例如,有些東西可能有更多的意見,並在31天前發佈。 – andy

1

如果你正在運行WordPress的3.7或更高版本,您現在可以使用date_query。沒測試過,不過您的查詢看起來像:

$popularpost = new WP_Query(array(
    'posts_per_page' => 33, 
    'meta_key' => 'wpb_post_views_count', 
    'orderby' => 'meta_value_num', 
    'order' => 'DESC', 
    'date_query' => array(
     array(
     'after' => '1 month ago', 
     'column' => 'post_date_gmt', //posted within one month 
    ), 
    ) 
    ) 
);