September 24, 2006
Recalculate WordPress comment count 1
find more posts in: ruby, wordpressSo I’ve been doing some work on the long-neglected Fontleech and today found myself removing over .25 million spam comments. That sounds herculean, but it was actually pretty easy.
The WordPress frontend pulls the comment count for each post from the ‘comment_count’ field in the wp_posts table. obviously that doesn’t get updated when you manually delete spam directly from the database, so here’s a simple ruby script that will update that for you (just define your db variables):
#!/usr/bin/ruby require 'mysql' db = Mysql.real_connect(host, user, pass, dbname) ids = db.query("SELECT `ID` FROM `wp_posts` WHERE 1") ids.each_hash do |post| id = post['ID'] num = 0 comments = db.query("SELECT COUNT(1) FROM `wp_comments` WHERE `comment_post_ID`='#{id}' AND `comment_approved`='1';") comments.each {|x| num = x[0]} up = db.query("UPDATE `wp_posts` SET `comment_count`='#{num}' WHERE `ID`='#{id}';") end
1 Response
Leave a Reply
My name is Joey Nelson. I'm a web developer living in Portland, OR. I'm married to an awesome lady and we have two weird little pugs. I do a weekly comedy podcast and make dumb songs with this guy Ben. I don't post to this blog very often, and very few people actually read it. If you'd like to find out more about my fascinating life, check this stuff out:
Stuff
Track me
Visit my sites
Visit my friends
Latest posts
Categories
- art
- audio
- baseball
- bikes
- books
- browsers
- complaints
- crime
- death
- dumb things
- energy
- environment
- family
- friends
- gadgets
- internet
- itunes
- life
- los angeles
- marriage
- movies
- music
- mysql
- new york
- os x
- pasadena
- photos
- php
- plugins
- podcasting
- politics
- portland
- pugs
- rss
- ruby
- splideo
- subversion
- ubuntu
- video
- watir
- wordpress
- work
Hey Joey, I have this problem too but I dont idea how to make this working.
Would you mind telling me how I execute the script?