WordPress Consultant and Genesis Developer

Fetch total custom post type count

I recently was working on my own Genesis CRM (similar to what Bill Erickson has released).

Unlike the other CRMs out there I decided to create a custom post type for my contacts instead of doing a bunch of magic to use posts. In a few places throughout the app I needed to pull the total number of contact entries in the database.

Turns out, it is very easy to do! Just a few lines of code, which you can see below. Make sure and change contact to the name of your post type.

function ja_total_post_count() {
	global $wpdb;
	$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'contact'");
	if (0 < $numposts) $numposts = number_format($numposts);
	return $numposts;
}
// To use...
echo 'Number of total contacts: ' . ja_total_post_count();