0

I would like to display custom posts in template, they have to be ordered by most commented and without duplicates on the same page. This is the code that I have for now.

$args = array(
'post_type' => 'portfolio',
'status' => 'approve',
'post_status' => 'publish',
'number' => 28,
'order' => 'ASC',
'orderby' => 'comment_count',
);
$comments = get_comments($args);
if ($comments) {
    foreach ($comments as $comment) : ;
        $post_args = array(
            'post_type' => 'portfolio',
            'posts_per_page' => 1,
        );
        $posts = get_posts($post_args);
        foreach ($posts as $post) : setup_postdata($post);
            $title = get_the_title($comment->comment_post_ID);
            ?>
            <div class="col-md-3 col-sm-6 col-xs-12">
                <h4><?php echo $title; ?></h4>
            </div>
        <?php
        endforeach;
    endforeach;
}

?>
<?php wp_reset_query(); ?>

1 Answer 1

0

Currently, it looks like you are looping through comments and then querying the posts from there. Could you use the comment_count order by parameter directly in the posts query itself?

For example:

<?php
$post_args = array(
    'post_type' => 'portfolio',
    'posts_per_page' => 1,
    'orderby' => 'comment_count'
);
$posts = get_posts($post_args);
foreach ($posts as $post) : setup_postdata($post);
    $title = get_the_title($comment->comment_post_ID);
    ?>
    <div class="col-md-3 col-sm-6 col-xs-12">
        <h4><?php echo $title; ?></h4>
    </div>
<?php
endforeach;

Source: https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters

1
  • 1
    Cannot believe that I've missed that. I feel like a jackass now, thanks for slaping me in the face! :)
    – unforgiven
    Commented Jan 14, 2020 at 23:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.