0

Currently my posts display the total count of comments (i.e both replies and sub-comments).

I want to display only the number of reply count in my index.php (and not comments for a reply) for each post i.e. where comment_parent = 0

I have tried different codes but no luck. What's the best way to acheive this?

  • @toscho I just went through your answer in a similar question. Am new to wordpress. Can you tell me how do I integrate your code in index.php to show the top-level comment count for each post. cheers! – Yusuf Alii Apr 10 '13 at 10:08
  • @toscho I tried your code by pasting it in the functions.php but still am getting the count for all the replies and comments instead of just the top-level comments. Am I missing something? – Yusuf Alii Apr 10 '13 at 10:40
  • I tested this local before I posted it here. It works. Try to collect debug information to see if something went wrong. – fuxia Apr 10 '13 at 10:45
0

Based on this answer I suggest the following code:

// the theme's functions.php

/**
 * Get the number of top level comments for a post.
 *
 * @param  int $post_id
 * @return int
 */
function wpse_95242_top_level_comments_for_post( $post_id = NULL )
{
    if ( NULL === $post_id )
        $post_id = get_the_ID();

    if ( ! $post_id )
        return 0;

    add_filter( 'comments_clauses', 'wpse_95242_where_top_comments_only' );

    $comments = get_comments(
        array (
            'post_id' => $post_id
        )
    );

    remove_filter( 'comments_clauses', 'wpse_95242_where_top_comments_only' );

    if ( ! $comments )
        return 0;

    return count( $comments );
}

/**
 * Filter comment query for top level comments.
 *
 * @wp-hook comments_clauses
 * @param   array $clauses
 * @return  array
 */
function wpse_95242_where_top_comments_only( $clauses )
{
    $clauses['where'] .= ' AND comment_parent = 0';
    return $clauses;
}

In your loop you call the function on each item:

printf(
    __( '%d top level comments', 'theme_text_domain' ),
    wpse_95242_top_level_comments_for_post()
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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