Support » Fixing WordPress » display count of posts in one category only?

  • I would like to be able to display the number of posts made over all time in one category. WordPress already displays the number of posts in each category, but I want to display the total for a particular category separately on the home page.

    Is there a simple way of doing this with WordPress without writing a new database query?

    (I am using WordPress to power a dog rescue site. Each post is about one dog, and when a dog is rehomed, it moves from the ‘I need a home’ category to ‘rehomed’. We would like to show a banner on the home page displaying the total number of dogs rehomed since the site started.)

Viewing 3 replies - 1 through 3 (of 3 total)
  • That’s going to require special coding. Maybe someone can come up with something, or consider adding a number manually instead of letting WordPress do it for you.

    The only trigger that would “count” up would be the movement of one post from the “need home” category to the “rehomed” category and changes like that, I don’t know if they could trigger a count.

    That’s really a special request. Maybe someone creative and expert enough might come up with such a plugin….you never know.

    I think I can probably write the query myself (not well enough to write a plugin, but well enough that it will work on this one site for this one task anyway!)

    I *think* what I need to do is query the post2cat table for all the records that have the ‘rehomed’ category ID, then count how many records there are.

    I was hoping it might have been something that had come up before as I am sure my version will be much longer and less elegant than proper WordPress code, but never mind!

    Ok, just in case anyone else wants to do this, this is how I did it:

    I put my database name and password in wp-config.php like this:

    $oldiesdb = mysql_connect(“host”, “user”, “pass”); // This is duplicating stuff WordPress already does, but hampered by my tiny brain, I found this easier.
    $oldiesdb_name = “dbname”;

    Then, in my index.php template, I added :

    mysql_select_db($oldiesdb_name,$oldiesdb)or die(“Error connecting to Database!
    ” . mysql_error());
    $rehomed = mysql_query(“SELECT * FROM wp_post2cat where category_id = 9″,$mydb); // select the records in the correct category, and store them as $rehomed
    $num_rows = mysql_num_rows($rehomed); //how many rows are there in $rehomed?

    echo “$num_rows Dogs listed on this website have found a home since April 2005! “; //Display the total number of rows as HTML text.

    You can see it on (Near the bottom – ‘Ted Says’.)

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘display count of posts in one category only?’ is closed to new replies.