Get Separate Count For Comments Trackbacks And Pingbacks In WordPress

fre, mar 12, 2010

Engelske guides, PHP/Mysql

The code

Place the code bellow in your theme’s functions.php file.

function commentCount($type = 'comments'){

	if($type == 'comments'):

		$typeSql = 'comment_type = ""';
		$oneText = 'One comment';
		$moreText = '% comments';
		$noneText = 'No Comments';

	elseif($type == 'pings'):

		$typeSql = 'comment_type != ""';
		$oneText = 'One pingback/trackback';
		$moreText = '% pingbacks/trackbacks';
		$noneText = 'No pinbacks/trackbacks';

	elseif($type == 'trackbacks'):

		$typeSql = 'comment_type = "trackback"';
		$oneText = 'One trackback';
		$moreText = '% trackbacks';
		$noneText = 'No trackbacks';

	elseif($type == 'pingbacks'):

		$typeSql = 'comment_type = "pingback"';
		$oneText = 'One pingback';
		$moreText = '% pingbacks';
		$noneText = 'No pingbacks';

	endif;

	global $wpdb;

    $result = $wpdb->get_var('
        SELECT
            COUNT(comment_ID)
        FROM
            '.$wpdb->comments.'
        WHERE
            '.$typeSql.' AND
            comment_approved="1" AND
            comment_post_ID= '.get_the_ID()
    );

	if($result == 0):

		echo str_replace('%', $result, $noneText);

	elseif($result == 1): 

		echo str_replace('%', $result, $oneText);

	elseif($result > 1): 

		echo str_replace('%', $result, $moreText);

	endif;

}

Change the $oneText, $moreText, $noneText variable values to suit your needs. The percentage character (%) can be used in all of the variables and will be replaced with the number.

Using the code

commentCount(); //echoes the comment count

commentCount('comments'); //same as the example on top

commentCount('pings'); //echoes number of trackbacks and pingbacks

commentCount('trackbacks'); //echoes number of trackbacks

commentCount('pingbacks'); //echoes number of pingbacks

If you know a simpler way to do this let me and the readers know in the comments. Thanks.

No tags for this post.

Related posts

Comments are closed.