Categories
Technology

Reseting Post and Comment Count in WordPress

I had faced a problem a few weeks back when I had tried to upgrade my WordPress install from 2.6.1 to 2.6.2. I was using the WP Automatic Upgrade plugin to upgrade my install, and it failed. Screwed up my database. Restoring from an SQL backup didn’t work either, strangely. Spent a few agonizing hours on the WordPress IRC channel and trying the stuff the helpful people there were suggesting but in the end it boiled down to this – short of doing a clean install there seemed no way out.

Thankfully I had also exported a WordPress Extended RSS (WXR) backup file (along with the SQL backup) before starting the upgrade process, so I was able to manually do a clean install of WordPress and then use WXR XML file to restore my blog. Before removing the old install I had already kept a copy of the wp-content directory on my host, so that when the XML import process was done recreating the file structure I could simply replace that with the copy I had moved to another folder. I learned a valuable lesson too – using the WP-AU might save you some time, but the consequences if something goes wrong are far-reaching and potentially ‘devastating’. My advice to fellow WP users is to use the manual update procedure no matter what. I shudder to think if the auto-upgrade functionality the developers intend to include in WordPress 2.7 fails, then a lot more users will be affected. (Since the feature will be available in the core install from now on, possibly a much greater number of users will be using it and will be at risk of something going wrong.)

Anyway, after doing the import I noticed that a few things were amiss. The first thing was that the category count for all posts was showing up as zero (and neither did the post management page show the categories under which a post was filed). This can be particularly irritating if you use a template (like mine) which displays the number of posts in a category in the sidebar. The solution for this is simple: create a post and file it under every category you have and publish it. This ‘forces’ WordPress to do a recount of the number of posts in for each category and the count is updated. You can then delete that post. Maybe ‘forces’ would be a strong word; WordPress counts the number of posts under a category any time you make a post.

Another note regarding post categories after importing from an WXR file it that if you were using a custom name for your ‘Uncategorized’ category, then you need to delete the custom category name (which will show up separately) and then rename the ‘Uncategorized’ category to whatever custom name you want.

The biggest problem I faced after the import was the fact that the comment count for each post was showing up as zero. Now you could do this the ‘hard way’ – similar to the post category update, you could go and make a new comment on each and every post you have (which would trigger WordPress to do a recount), and then delete those comments. Admittedly that would be stupid and time-consuming especially if you have a blog like mine which has hundreds of posts. So for this, here’s what you need to do:

  1. Save the script below as a *.php file using a text editor. Name it something like filename.php or whatever you feel like; just keep in mind NOT to give it a filename same as already-existing WordPress files on your host. Change the ‘wp_’ prefix to whatever your installation has, in case you changed it.
  2. Upload the PHP file to the root folder of your WordPress install.
  3. Navigate to the file at yourblogname.com/filename.php using your web browser (using your own blog and file name).
  4. Remember to remove the file after you’re done.

So use the comment count update script below to automate the comment count update process. Before running the script, it would be a good idea to create a backup of your existing database, just case something goes wrong. If the comment doesn’t seem to work then your text editor is probably breaking something. Remove all newline characters manually.

<?php

/* This program is free software: you can redistribute it and / or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. For a copy of the GNU General Public License see http://www.gnu.org/licenses/gpl.html */

/* Script to recount number of comments in WordPress install. This script has been tested with WordPress 2.6.x. Note that script may fail to run the update for all posts in case the script runs longer than the timeout period specified in your settings. In case that happens, try increasing the timeout limit by editing the php.ini file on your webhost. If you are unable to modify the php.ini file and / or don't have access to it then just say a quick prayer and hit the 'Reload' button on your web browser. */

include('wp-config.php'); // Needed for login details to WordPress database to make necessary changes

function updateCount()
    {
        $posts = mysql_fetch_row(mysql_query("SELECT ID FROM wp_posts ORDER BY ID DESC LIMIT 1")); // Fetch row in WordPress database containing information about post data
        for ($i = 1; $i < ($posts[0] + 1); $i++)
        {

     $comments = mysql_query("SELECT SQL_CALC_FOUND_ROWS comment_ID FROM wp_comments WHERE comment_post_ID = '$i' AND comment_approved = 1;") or die("Failed to calculate number of approved comments"); // Calculate the number of approved comments for a post and store in a variable. If unsuccessful, end program.

     mysql_query("UPDATE wp_posts SET comment_count = '".mysql_num_rows($comments)."' WHERE id = '$i';") or die("Failed to update the number of comments calculated"); // Update the comment count using the comment number fetched earlier. If unsuccessful, end program

     echo "Updated Post #$i - ".mysql_num_rows($comments)." comments <br />"; // Display message to user for each post comment count successfully updated
        }
    }

updateCount();
?>
Categories
Personal Reflections

Code Wars 2008. It’s On.

Code Wars 2008 is firmly on schedule now – on 21st November 2008. It was earlier supposed to happen on 14th (Google search still gives the old date)…but due to a few circumstances and popular demand it was thought it would be best to shift it back). That would make for one hectic week, with WarP (DPS Mathura Road’s), CORE (DPS Dwarka’), our event Code Wars, and DPS MUN happening back to back (and soon followed by Exun). Seems like DPS Society schools are hogging all the space this month!

It was a difficult decision to distill Code Wars 2008 down to one day, but it was done to retain the standard of the event. The economic recession did hit us badly with almost all companies cutting down on their advertisement budget. Thankfully, Renew Information Systems and NIIT pitched…and we had an event. The interest shown to support the event by MapMyIndia – started by Code Warrior alumnus Rohan Verma – at a stage when the CW team was in dire straits gave us confidence to go ahead with this. Continuing with tradition, Code Wars 2008 is an open invite event, i.e., in case your school hasn’t got an invite through postal mail yet, then you can download the invite and rules and come for the event anyway (the downloaded versions are equally valid). Remember to register your school online – it’s mandatory.

By cutting it down to a one-day event, we decided to raise the difficulty level across all events. That should keep the excitement up. (Or maybe we’ll just have teams sobbing they couldn’t answer anything.) I’ll be conducting the quiz and crossword and I can vouch this for my events at least. I’m sure a lot of people who’d be coming read my blog so this is my message to them: you still have about a week left. Start preparing. Broaden your horizons and read up stuff like crazy. If you don’t, you won’t know what hit you in the quiz / crossword. Similar to last year, I’ve tried to incorporate knowledge of multiple fields (beyond tech / computers), so be prepped to think outside the box. To make life easier for everyone I’ve decided NOT to include any acronyms (‘mini Ankit Sud’ from DPS Dwarka will be dejected). It pains me when I see kids frantically flipping pages through Babel minutes before an event. Range of topics covered? Everything (except for a slightly less focus on tech, more of trivia; although you may say that there might be a slight bias in covering more of stuff. I. like.) Crossword will be a ‘monster’ crossword with a LOT of clues.

Code Wars 2008 has also had some format changes. Since every event can’t be fitted into a one-day fest, it was decided that we’d hold web designing and digital imaging online. Details are there on the Code Warriors website. I sure look forward to some creative entries!

There’s a funny anecdote here regarding a company which was approached for sponsorship for Code Wars 2008. This kind of stuff is not something I’d discuss generally, but the kind of hypocrisy displayed was so astonishing that I feel I must share it. Among the companies the current CW members approached was Virgin Mobile; their corporate office is in Vasant Square Mall, darn close to our school. So our guys met this woman who was in their marketing department about Virgin Mobile sponsoring us. I gave them the idea about approaching them since it makes perfect sense for Virgin to sponsor us – after all, their brand is targetting the youth segment and an event like Code Wars would give them valuable exposure without Virgin having to pump in a lot of money (unlike college events). Seems like DPS RKP had approached them too because at first she mixed up VK and RKP. Anyway, she heard the team out and in the end she said they won’t sponsor us because

…DPS schools have a slightly shady reputation when it comes to cellphones…

I mean, really? That was ages ago. And this is a lecture on propriety coming from a company which releases ads like the hospital nurse one. I don’t object to the ad which was good, but I do find it ironic that someone from Virgin Mobile’s marketing department said this. More ironic when you consider that Richard Branson owns the company. Maybe this Virgin Mobile lady wasn’t there at the launch of Virgin Mobile (this video, BTW, was put up by Virgin Mobile India’s own marketing department). Talking of ‘reputation’, Airtel has sponsored Code Wars – twice – in the past. Admittedly a company with much greater reputation. CW’s sponsor list has had Microsoft, Intel, Lenovo et al – a veritable who’s who of top tech companies. Virgin Mobile India must be kidding to throw away the marketing opportunity we gave them on those grounds.

See you at Code Wars 2008. soBIG.g. It’s on.