2017-02-12 93 views
2

我想顯示上個月最特定類別的評論文章。 這是我現在的代碼,我無法弄清楚這裏有什麼錯,有什麼想法?顯示最近評論的帖子上個月wordpress

<?php 
function filter_where($where = '') { 
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'"; 
    return $where; 
       } 

    add_filter('posts_where', 'filter_where'); 
    $the_query = new WP_Query(array('posts_per_page' => 3, 'cat' => 2, 'orderby' => 'comment_count date', 'order'=> 'DESC')); 

    remove_filter('posts_where', 'filter_where'); 
       ?> 
    <?php while ($the_query->have_posts()) : $the_query->the_post(); 
        echo get_the_title(); 
        // and rest of content 
    endwhile; 
wp_reset_postdata(); ?> 

編輯:p.s.順便說一句,我正在使用Vkontakte Api插件爲我的意見。可能是問題出在這裏,因爲這段代碼在其他站點上確實可以正常工作。但是,get_comments_number()顯示正確的數字,爲什麼然後orderby => comment_count不起作用?

回答

0

您必須爲此使用date_query

$args = [ 
    'posts_per_page' => 3, 
    'post_type' => 'post', 
    'date_query' => [ 
     [ 
      'year' => date('Y', strtotime(date('Y-m-d') . " -1 month")), 
      'month' => date('m', strtotime(date('Y-m-d') . " -1 month")) 
     ] 
    ], 
    'orderby' => 'comment_count', 
    'order' => 'DESC' 
]; 
$posts = new WP_Query($args); 
//$posts = get_posts($args); 
//print_r($posts); 


MySQL查詢將是獲得上個月的熱門職位將是:( 假設NOW() = 2017年2月13日

SELECT 
    posts.ID, 
    posts.post_title, 
    posts.post_date 
FROM 
    wp_posts AS posts 
WHERE 
    YEAR (posts.post_date) = 2017 
AND MONTH (posts.post_date) = 1 
AND posts.post_type = 'post' 
AND posts.post_status = 'publish' 
ORDER BY 
    posts.comment_count DESC 
LIMIT 0, 3; 

希望這有助於!

+0

不幸的是,這並沒有幫助。無論如何,謝謝 – Dolohov

+0

@Dolohov:你可以運行MySQL並讓我看看是否收到任何文章?只需將你的表格前綴替換成你的。 –

+0

我正在接受他們。但不按comment_count排序。順便說一句,我添加了一些更多的信息昨天,IDK,如果你注意到或不 – Dolohov