我使用Ribbon主题,它有一个很好的选项卡式小部件,显示最流行和最新的帖子。我想把最受欢迎的帖子限制在过去12个月。我宁愿不使用插件,而是更改主题文件中的代码。查询如下:
function mts_popular_tabs( $posts = 5 ) {
    $popular = new WP_Query(\'showposts=\'. $posts .\'&orderby=comment_count&order=desc\');
    $popular_post_num = 1;
    while ($popular->have_posts()) : $popular->the_post();
 我尝试了以下片段:
function filter_where($where = \'\') {
        $where .= " AND post_date > \'" . date(\'Y-m-d\', strtotime(\'-365 days\')) . "\'";
        return $where;
}
add_filter(\'posts_where\', \'filter_where\');
 它适用于小部件,但也会影响其他查询。我试图卸下过滤器,但没有成功:
wp_reset_query();
remove_filter(\'posts_where\', \'filter_where\');
 我试图这样重写查询,但没有成功:
$today = date(\'Y-m-d\');
$todayminusone = date(\'Y-m-d\', strtotime(\'-1 year\'));
$args = array(  
    \'date_query\' => array(  
        array(  
            \'after\' => $today,  
            \'before\' => $todayminusone,  
        ),  
    ),  
    \'showposts\' => 5,
    \'orderby\' => \'comment_count\',
    \'order\' => \'desc\'  
); 
function mts_popular_tabs() {
    $popular = new WP_Query($args);
    $popular_post_num = 1;
    while ($popular->have_posts()) : $popular->the_post();
 我被困在这里了。任何帮助都将不胜感激。
谢谢你的帮助。这是我现在使用的代码:
function mts_popular_tabs( $nr = 5 )
{
    $args = array(  
        \'date_query\'     => array( array( \'after\' => \'-1 year\' ) ),  
        \'posts_per_page\' => (int) $nr,
        \'orderby\'        => \'comment_count\',
        \'order\'          => \'DESC\'  
    ); 
    $popular = new WP_Query( $args );
    $popular_post_num = 1;
while ($popular->have_posts()) : $popular->the_post();
    ...
 
                    最合适的回答,由SO网友:birgire 整理而成
                    正如@Rarst所建议的,你必须$args 在函数中定义。您可以使用全局变量来解决它,但我们don\'t want 这样的变数太多了!
查看上的PHP文档the scope of a variable 或者在class.
您还可以简化查询。下面是一个函数的示例:
function mts_popular_tabs( $nr = 5 )
{
    $args = array(  
        \'date_query\'     => array( array( \'after\' => \'-1 year\' ) ),  
        \'posts_per_page\' => (int) $nr,
        \'orderby\'        => \'comment_count\',
        \'order\'          => \'DESC\'  
    ); 
    $popular = new WP_Query( $args );
    // ... your loop ...
    wp_reset_postdata();
}
 这将生成以下SQL查询:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 
    FROM wp_posts 
    WHERE 1=1 
          AND ( ( post_date > \'2013-04-06 11:30:26\' ) ) 
          AND wp_posts.post_type = \'post\' 
          AND (wp_posts.post_status = \'publish\') 
    ORDER BY wp_posts.comment_count DESC 
    LIMIT 0, 5 
 如果当前日期为
\'2014-04-06 11:30:26\'.
附言:如果您想要posts_where 筛选以仅影响的实例WP_Query, 还应将其移动到函数中:
function mts_popular_tabs( $nr = 5 )
{
    add_filter( \'posts_where\', \'filter_where\' );
    $popular = new WP_Query( $args );
    remove_filter( \'posts_where\', \'filter_where\' );
    // ... your loop ...
    wp_reset_postdata();
}
 但在这种情况下你不需要它。
希望这有帮助。