4

I selected only 2 levels of comment for my wordpress site. How can I display the number of comment of the first level ? (Depth-1)

1
  • Where did you select to "use" two levels of comments? Are you trying to retrieve the number of 1st-level comments while ignoring (not counting) all of those beneath the 1st level? Where are you trying to display this number? – bosco Jan 7 '13 at 23:52
2

In the wp_comments table, if comment_parent equals 0, it's a first-level comment.

function get_num_toplevel_comments() {
    global $wpdb;

    return $wpdb->get_var("
        SELECT COUNT(*) 
        FROM $wpdb->comments
        WHERE comment_parent = 0
    ");
}
1
  • 2
    @toscho - sorry to comment here, I'm not yet able to comment elsewhere. Your function retrieves all of the top-level comments in their entirety. @ Mathieu specifically asked in two separate places in the question for just the number of top-level comments. Your answer did teach me a new hook though! Virtual +1 :) – akTed Jan 8 '13 at 11:05
2

Based on akTed's answer:

function get_top_level_comments_number( $post_id = 0, $onlyapproved = true ) {

    global $wpdb, $post;

    $post_id = $post_id ? $post_id : $post->ID;

    $sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_parent = 0 AND comment_post_ID = $post_id";

    if( $onlyapproved ) $sql .= " AND comment_approved='1'";

    return (int) $wpdb->get_var( $sql );

}

Usage same as here … Returns the number of top level comments for a specific post (or the current one if no id is given)

2
  • 1
    I add condition for approved and convert to int type return (int) $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_parent = 0 AND comment_post_ID = $post_id AND comment_approved='1'" ); – kostikovmu Apr 21 at 10:30
  • @kostikovmu Yeah makes totally sense. I've updated my answer. – GDY Apr 22 at 10:36
0

Use the code from this answer and remove just one !:

add_filter( 'comments_clauses', 'wpse_78628_top_comments_only' );

$comments = get_comments();

remove_filter( 'comments_clauses', 'wpse_78628_top_comments_only' );

function wpse_78628_top_comments_only( $clauses )
{
    $clauses['where'] .= ' AND comment_parent = 0';
    return $clauses;
}
1
  • Fantastic work.:) worked like a charm :) – Rohit Pande Jan 8 '13 at 10:26
0

here is some full working code, based on previous answers.

  <?php
add_filter( 'comments_clauses', 'wpse_78490_child_comments_only' );

function wpse_78490_child_comments_only( $clauses )
{
    $clauses['where'] .= ' AND comment_parent != 0';
    return $clauses;
}
  $count = get_comments( array('post_id' => $post->ID, 'count' => true) ); echo $count; ?>

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.