Using WordPress ‘get_comment_type()’ PHP function

The get_comment_type() WordPress PHP function retrieves the comment type of the current comment or a specified comment.

Usage

get_comment_type( $comment_id );

Example

$comment_type = get_comment_type( 15 );
echo $comment_type; // Outputs the comment type, e.g. 'comment', 'pingback', 'trackback', or an empty string for other types.

Parameters

  • $comment_id (int|WP_Comment, optional): WP_Comment or ID of the comment for which to get the type. Default is the current comment.

More information

See WordPress Developer Resources: get_comment_type()

Examples

Display comment type for a specific comment

This example displays the comment type for a comment with the ID of 5.

$comment_id = 5;
$comment_type = get_comment_type( $comment_id );
echo "Comment Type: " . $comment_type;

Display comment types for all comments in a post

This example displays comment types for all comments in a post.

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

foreach ( $comments as $comment ) {
    echo "Comment Type: " . get_comment_type( $comment );
}

Display comment count by type

This example displays the number of comments, pingbacks, and trackbacks in a post.

$comment_count = array( 'comment' => 0, 'pingback' => 0, 'trackback' => 0 );
$comments = get_comments( array( 'post_id' => get_the_ID() ) );

foreach ( $comments as $comment ) {
    $type = get_comment_type( $comment );
    if ( isset( $comment_count[$type] ) ) {
        $comment_count[$type]++;
    }
}

echo "Comments: {$comment_count['comment']} Pingbacks: {$comment_count['pingback']} Trackbacks: {$comment_count['trackback']}";

Display only comments, excluding pingbacks and trackbacks

This example displays only comments, excluding pingbacks and trackbacks, for a post.

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

foreach ( $comments as $comment ) {
    if ( 'comment' === get_comment_type( $comment ) ) {
        echo $comment->comment_content;
    }
}

Add a custom CSS class based on the comment type

This example adds a custom CSS class to the comment content based on the comment type.

function my_comment_callback( $comment, $args, $depth ) {
    $comment_type = get_comment_type( $comment );
    $css_class = 'comment-' . $comment_type;
    echo '<div class="' . $css_class . '">' . $comment->comment_content . '</div>';
}

wp_list_comments( array( 'callback' => 'my_comment_callback' ) );