get_comments_number of depth-1 (Level 1) (1 post)

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)

Related posts

Leave a Reply

4 comments

  1. 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
        ");
    }
    
  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)

  3. 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;
    }
    
  4. 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; ?>