Retrieving The Total Number of Posts from a Specific Custom Post Type WordPress Taxonomy

The function bellow can be used to retrieve the total number of posts from a specific custom post type taxonomy in WordPress sites. There are only two steps, supposing you’ve registered a custom post type video and a taxonomy genre as I show on a previous post.
A função abaixo pode ser usada para retornar o número total de posts de uma taxonomia específica de um tipo de post customizado. São apenas dois passos, supondo que você criou um tipo de post customizado ‘video’ e uma taxonomia ‘genre’ como eu mostro em um post anterior.

Step 1:

<?
// put this code on your functions.php file, on your theme directory
// the function use the custom post type registration and the taxonomy slug as parameters
function wt_get_custom_taxonomy_count($ptype,$pterm) {
	global $wpdb;
	$SQL  = "SELECT count(*) FROM $wpdb->posts posts, $wpdb->terms terms, $wpdb->term_relationships rels ";
	$SQL .= "WHERE posts.post_status = 'publish' ";
	$SQL .= "AND post_type = '".$ptype."' ";
	$SQL .= "AND posts.ID = rels.object_id ";
	if($pterm!=""):
	$SQL .= "AND terms.slug = '".$pterm."' ";
	endif;
	$SQL .= "AND terms.term_id = rels.term_taxonomy_id";
	return $wpdb->get_var($SQL);
}
?>

Step 2:

<?
// put this on the theme page where you want the info to show
echo wt_get_custom_taxonomy_count('video','genre');
?>

This code can be very useful to be used when you are working on a WordPress custom taxonomy page.
Este código pode ser bastante útil quando você está trabalhando em uma página de taxonomia customizada do WordPress.

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: