WP_QUERY仅包含评论的帖子

时间:2016-04-04 作者:anyway

我需要一个灵活的解决方案来列出一个带有评论的帖子列表。我正在尝试使此解决方案起作用,但运气不佳:https://wordpress.stackexchange.com/a/219216/91757

我总是得到正常的列表,就像在博客首页上一样。即使\'ignore_sticky_posts\' => true 不起作用。我做错了什么?以下是我目前的代码:

<?php function has_comments_join( $join, &$wp_query ) {
    global $wpdb;
    if ($comment_term = $wp_query->get(\'post_has_comments\')) {
        $join .= $wpdb->prepare(" JOIN $wpdb->comments ON (($wpdb->posts.ID = $wpdb->comments.comment_post_ID) AND ($wpdb->comments.comment_type = %s) AND ($wpdb->comments.comment_approved = %s)) ", $comment_term[\'comment_type\'], $comment_term[\'comment_status\']);
    }
    return $join;
}

$results = new WP_Query(array(

    \'post_type\'             => array( \'post\' ),
    \'ignore_sticky_posts\'   => true,
    \'posts_per_page\'        => 8,
    \'order\'                 => \'dsc\',

    \'post_has_comments\' => array(
        \'comment_type\' => \'review\',
        \'comment_status\' => \'1\'
    )
)); ?>  

<?php while ( $results->have_posts() ): $results->the_post(); ?>
    <?php get_template_part( \'parts/loop\', \'archive\' ); ?>
<?php endwhile; ?>
现在一切正常,除了分页:

<?php   
function my_has_comments_filter( $where ) {
    $where .= \' AND comment_count > 0 \';
    return $where;
}
add_filter( \'posts_where\', \'my_has_comments_filter\' );
$paged = ( get_query_var(\'page\') ) ? get_query_var(\'page\') : 1;
$query = new WP_Query( array(
    \'posts_per_page\'        => 8,         
    \'paged\'                 => $paged,
    \'ignore_sticky_posts\'   => true,
    \'order\'                 => \'dsc\',
) );
// Don\'t filter future queries.
remove_filter( \'posts_where\', \'my_has_comments_filter\' ); ?>

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

    <?php get_template_part( \'parts/loop\', \'archive\' ); ?>

<?php endwhile; ?>
    <?php joints_page_navi(); ?> // Does not work with original WP code too
    <?php wp_reset_postdata(); ?>

<?php else : ?>

    <?php get_template_part( \'parts/content\', \'missing\' ); ?>

<?php endif; ?>

1 个回复
最合适的回答,由SO网友:kovshenin 整理而成

如果要更改WP_Query, 您需要使用posts_join 过滤器,或者在您的情况下,更容易posts_where:

function my_has_comments_filter( $where ) {
    $where .= \' AND comment_count > 0 \';
    return $where;
}

add_filter( \'posts_where\', \'my_has_comments_filter\' );
$query = new WP_Query( array(
    \'posts_per_page\' => 10,
) );

// Don\'t filter future queries.
remove_filter( \'posts_where\', \'my_has_comments_filter\' );
希望有帮助!