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.

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?

share|improve this question
    
@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! –  Gina 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? –  Gina 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. –  toscho Apr 10 '13 at 10:45

1 Answer 1

up vote 0 down vote accepted

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()
);
share|improve this answer
    
thanks, that worked like a charm! –  Gina Apr 12 '13 at 10:38

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.