Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

This may sound like an unusual request but I am try to display comments from several related posts in a single comment template.

For example I have several posts on the same topic (IDs 253, 724, 798) and I want all comments from these posts to appear next in a continuous thread. So if I am viewing post ID 724 I can also see the comments from posts 253 and 798.

Can I pass multiple post IDs to the comments template to achieve this does this require a custom query before or after the comments template to show all the comments in a merged thread?

share|improve this question
add comment

2 Answers

you can get comments from each post by its id with

$comments253 = get_comments('post_id=253');
$comments724 = get_comments('post_id=724');
$comments798 = get_comments('post_id=798');

then merge ( array-merge ) and sort the array by date ( comment->comment_date being the key to the date value) if you want. then just

 foreach($comments as $comment) :
      echo($comment->comment_author . '<br />' . $comment->comment_content);
 endforeach;

This is all very manual, and you might want to automatize the process, but that's probably an different matter.

share|improve this answer
add comment

Getting the comments for multiple posts is rather simple: Just replace comment_post_ID = YOUR_POST_ID with an IN() function.

function wpse_59687_multiple_comment_post_id_query_filter( $query )
{
    $post_ids = array ( 149, 188, 151 );
    if ( FALSE === strpos( $query, 'comment_post_ID = ' ) )
    {
        return $query; // not the query we want to filter
    }

    remove_filter( 'query', 'wpse_59687_multiple_comment_post_id_query_filter' );

    $replacement = 'comment_post_ID IN(' . implode( ',', $post_ids ) . ')';
    return preg_replace( '~comment_post_ID = \d+~', $replacement, $query );
}

Now you call this function just before you call comments_template():

add_filter( 'query', 'wpse_59687_multiple_comment_post_id_query_filter' );

What’s more difficult:

  • get_comments_number() is wrong. You have to filter its value too.
  • Replies to a comment from another post are redirected to the URL of the other post, not the page where the commenter has written the comment. Fixing that will be not so trivial …
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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