Comment count in WordPress shortcode

Earlier today I was raving about the simply elegant plug-in Anti-Spam. When writing that post, it occurred to me that I specified two pieces of information that might change as time passes. If you’ve read my post on dynamic ages in my About Me page, then it might be obvious…

Earlier today I was raving about the simply elegant plug-in Anti-Spam. When writing that post, it occurred to me that I specified two pieces of information that might change as time passes.

If you’ve read my post on dynamic ages in my About Me page, then it might be obvious that I like to keep things dynamic. That is to say, I don’t like to use static values unless those values are simply a snapshot in time. So I thought I’d add a little functionality to my site that would:

  • determine how much time has passed, given a start date
  • allow me to obtain the number of spam comments I have

The first part was rather easy, as I’ve already added a shortcode that determines a person’s age. It was simply a matter of modifying this code to account for smaller frames of time, as well as more generic frames of time (“only 2 days”, “over 3 years”).

I started by changing line #5 in my calcAge function to:

extract(shortcode_atts(array('birthdate' => '1970-11-24','detail' => false), $parameters));

This allowed me to specify that I wanted detailed time information by passing a “detail = true” argument in my shortcode.

I then needed to add code to create the detailed time information. To accomplish this, I added the following code above the “return $results” line in the code listed in my dynamic ages post:

// Additional code to accommodate for smaller times
if($detail == true)
{
	if($years == 0)
	{
		if($months == 0)
		{
			$weeks = floor($days / 7);
			if($weeks == 0)
			{
				$results = $days." day";
				if($days > 1)
				{	
					$results = $results."s";
				}	
			}
			else
			{
				$results = $weeks." week";
				if($weeks > 1)
				{
					$results = $results."s";
				}
			}
		}
		else
		{
			$results = $months." month";
			if($months > 1)
				$results = $results."s";
		}
	}
	else
	{
		$results = $years." year";
		if($years > 1)
			$results = $results."s";
	}
}

I then needed a way to get the number of spam comments on my site. I found the WordPress function get_comments and basically wrapped that in a function I could access with a shortcode. The get_comments function takes several optional parameters, but I was only interested in two – the ability to specify the type of comment I wanted (status=’spam’) and the ability to get just the count of the comments of specified type (count=’true’).

The WordPress function accepts an array of key-value pairs as a parameter, so it was just a matter of building the array, passing it to the get_comments function, then returning the results.

Here’s my code – this gets entered into my theme’s functions.php file, anywhere between the existing tags – but NOT inside another existing function.

function GetCommentCount($atts)
{
	extract(shortcode_atts(array('status' => 'spam', 'count' => true,), $atts));

	$args = array(
	'status' => $status,
	'count' => $count,
	);
	$comment_count = get_comments($args);

	if($comment_count == 0)
	{
		$results = "not received a single ".$status." comment";
	}	
	else
	{
		$results = "only received ".$comment_count." ".$status." comment";
	}
	if($comment_count > 1)
	{
		$results = $results."s";
	}
	return $results;
}

add_shortcode('GetCommentCount', 'GetCommentCount');

Let’s break this down.

extract(shortcode_atts(array('status' => 'spam', 'count' => true,), $atts));

Line #3 simply parses our shortcode parameters into PHP variables. Here, we’re extracting the ‘status’ and ‘count’ key-value pairs (KVPs) from the shortcode arguments, assigning them default values if necessary, then assigning the values of those KVPs to the $status and $count PHP variables.

    $args = array(
    'status' => $status,
    'count' => $count,
    );

In lines #5-#8 (broken down to multiple lines for easy reading; note that PHP lines are terminated with a “;”, not a carriage return), we’re building an array of KVPs and assigning them to the $args PHP variable. We’re specifying the ‘status’ key to have the value stored in the $status PHP variable, and the ‘count’ key to have the value stored in the $count PHP variable.

    $comment_count = get_comments($args);

In line #9, we’re passing the previously created array as arguments to WordPress’ get_comments function. By default, get_comments returns an array of comments. However, since we’re passing the KVP “‘count’ => ‘true’” as an argument, get_comments instead will return a single integer representing the number of comments represented by the $status value type.

    if($comment_count == 0)
    {
        $results = "not received a single ".$status." comment";
    }   
    else
    {
        $results = "only received ".$comment_count." ".$status." comment";
    }
    if($comment_count > 1)
    {
        $results = $results."s";
    }

In lines #11-22, we’re simply building a string to be returned based on the value returned by the call to get_comments. If get_comments returns a value of 0, then I’m setting $results to “not received a single spam comment” (using ‘spam’ as the $status value). Otherwise, we’re setting $results to “only received # spam comments” (again, using ‘spam’ as the $status value), where # = the value returned by the function.

Now, in my rave about the Anti-Spam plugin, I used the shortcodes as follows:

“I’ve had this plugin installed for over [calcAge birthdate=’2013-03-14′ detail=true] and have [GetCommentCount].”

There are numerous WordPress plugins that allow PHP code to be embedded in pages and posts. I use the cleverly named Allow PHP in Pages and Posts plugin, which allows me to embed PHP code inside [allowphp][/allowphp] tags. Note that if I only wanted the comment count of spam comments, for example, I could have simply placed a call to the WordPress get_comments function inside [allowphp][/allowphp] tags. However, I prefer to place this code in my functions.php file to prevent the WordPress editor from stripping any necessary characters.

+ ,

One response to “Comment count in WordPress shortcode”

Leave a Reply

Your email address will not be published. Required fields are marked *