WP LOGBOOK

Little adventures building sites with Wordpress…

How to display post count from a category

with 4 comments

I am just recording my work right now. I found this to work really well.


function wt_get_category_count($input = '') {
global $wpdb;
if($input == '')
{
$category = get_the_category();
return $category[0]->category_count;
}
elseif(is_numeric($input))
{
$SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->term_taxonomy.term_id=$input";
return $wpdb->get_var($SQL);
}
else
{
$SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->terms.slug='$input'";
return $wpdb->get_var($SQL);
}
}

Place above in your function.php file.

And then add below inside the regular php begin and end to any location you want the count to be displayed.
echo wt_get_category_count(categoryid);

Thanks to WPCode.net for the post here.

Advertisements

Written by Yahya Ayob

December 5, 2010 at 7:48 pm

Posted in coding, tutorial, WordPress

4 Responses

Subscribe to comments with RSS.

  1. Hi Yahya!

    How can I use the function when a post has two or more subcategories? I´m asking it because when it happens the number displayed under a category doesn´t match with the real number of posts.

    Thanks for help.

    Marcio Nunes

    December 7, 2010 at 5:08 am

  2. Thanks for the mention

    Wpcode.net

    January 27, 2011 at 3:34 am

    • No problemo! =)

      Yahya Ayob

      March 14, 2011 at 1:11 am

  3. Hi Yahya,

    This counts posts that have been trashed, anyway to stop that?

    ukcpi

    August 19, 2011 at 8:44 pm


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: