Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

get post count outside of workpress loop WordPress

I would like to display the post count of pages that have a particular taxonomy outside of the main page loop

Ideally this would be a function where I feed it the taxonomy slug and it returns the count of posts with that set.

For example on the page below I would like to be able to display a count of the employers in the menu like "members (1)" is. I also plan to use this in widgets

Answers (6)


Jatin Soni answers:

try this


$postcount = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");

echo $postcount;


npeplow comments:

Hi Jatin

How would that distinguish between the different taxonomy's?

Jatin Soni comments:

You mean count by taxonomy? Can you please describe in little detail.


John Cotton answers:

You're going to want to look at [[LINK href=""]]get_objects_in_term[[/LINK]].

function my_tax_count( $name ) {
$ids = get_terms( $name, array( 'fields' => 'ids' ) );

$objects = get_objects_in_term( $ids, $name );

return count($objects);

It doesn't do precisely what you want, but if you pass it a list of the ids in the term, then you could do a count on the result.

You could, of course, write a little custom SQL that does precisely what you want. Certainly you'd get far better performance, but with the downside that you risk things breaking if a future WP update changes the way things are structured in the database.


Luis Abarca answers:

This can work

wp_list_categories('include=' . $your_cat_ID);

Luis Abarca comments:

Also check this functions

[[LINK href=""]][[/LINK]]


Francisco Javier Carazo Gil answers:

Well, if you want to do this only for a taxonomy:


$postcount = $wpdb->get_var(";

FROM $wpdb->posts p
INNER JOIN $wpdb->term_relationships tr
ON p.post_id = tr.object_id
INNER JOIN $wpdb->terms t
ON t.term_id = tr.term_id
WHERE p.post_status = 'publish'
echo $postcount;



Arnav Joy answers:

i am not sure what i am giving is what you want , but try it

define it in functions.php
function returnCount($slug){
global $wpdb;
$row = $wpdb->get_row("SELECT tt.count FROM ".$wpdb->prefix."term_taxonomy tt LEFT JOIN ".$wpdb->prefix."terms t ON tt.term_id = t.term_id WHERE t.slug = '".$slug."'");
return $row->count;


and in the template use it as:-

$slug = 'uncategorized';
$count = returnCount($slug);
echo $count;


Rashad Aliyev answers:

$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
echo 'Count :' .$term->count;