Advertisement
SergeyBiryukov

Get comments with replies

Oct 19th, 2017
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.98 KB | None | 0 0
  1. function _get_child_comments( $clauses ) {
  2.     $clauses['where'] .= ' AND comment_parent > 0';
  3.     return $clauses;
  4. }
  5.  
  6. function get_comments_with_replies( $query ) {
  7.     if ( empty( $query->query_vars['with_replies'] ) ) {
  8.         return;
  9.     }
  10.  
  11.     remove_filter( 'parse_comment_query', __FUNCTION__ );
  12.     add_filter( 'comments_clauses', '_get_child_comments' );
  13.  
  14.     $child_comments = get_comments( $query->query_vars );
  15.  
  16.     remove_filter( 'comments_clauses', '_get_child_comments' );
  17.     add_filter( 'parse_comment_query', __FUNCTION__ );
  18.  
  19.     $parent_comment_ids = array();
  20.  
  21.     foreach ( $child_comments as $comment ) {
  22.         if ( ! in_array( $comment->comment_parent, $parent_comment_ids ) ) {
  23.             $parent_comment_ids[] = $comment->comment_parent;
  24.         }
  25.     }
  26.  
  27.     $query->query_vars['comment__in'] = $parent_comment_ids;
  28. }
  29. add_action( 'parse_comment_query', 'get_comments_with_replies' );
  30.  
  31. $comments = get_comments( array( 'post_id' => 123, 'with_replies' => true ) );
  32. echo '<pre>'; print_r( $comments ); echo '</pre>';
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement