WordPress: Flushing Spam Comments Quickly

While I love a well-configured copy of Spam Karma 2 as an effortless way to keep my blog free of spam, it doesn’t seem to have a way to automatically purge/expire comments after they sit in the spam bin for a while.

Until I can come up with a more automatic solution, here’s the simplest way to purge all binned spam in a few seconds using the phpMyAdmin SQL query window (it’s an icon in the sidebar once you’ve picked a database):

  1. Delete all comments marked as spam:
    DELETE FROM wp_comments WHERE comment_approved="spam";
  2. Look up all newly orphaned comment metadata entries:
    SELECT m.comment_id FROM wp_commentmeta AS m 
      WHERE (SELECT COUNT(c.comment_ID) FROM wp_comments AS c 
        WHERE m.comment_id = c.comment_ID) = 0;
  3. Click “Check All” at the bottom of the results list. (MySQL doesn’t let you subquery a table you’re deleting from)
  4. Click “Delete” to the right of “Check All”.

How much faster is this? In the same time it took me to purge 20 comments via the WordPress web interface, I used this process to remove the remaining thousand or so. The actual SQL statements took fractions of a second.

Still… this is a bit outside my usual area of SQL expertise (I normally work mostly with SQLite and simple INNER JOINs), so I welcome cleaner, more automatic ways to do this without resorting to a little PHP or Python script to pass lists of IDs between statements.

CC BY-SA 4.0 WordPress: Flushing Spam Comments Quickly by Stephan Sokolow is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

This entry was posted in Geek Stuff. Bookmark the permalink.

2 Responses to WordPress: Flushing Spam Comments Quickly

  1. albatroz says:

    I am in a situation where I need to purge the spam comments of a WordPress database.
    I have identified that I can delete IPs based on the value of the comment_author_IP field.
    BTW 199.83.131.2 is one of spammers IP.

    My doubt is if it is safe to delete the comments based on your criteria.
    Is the table wp_254_comments the only that stores comments information?

    • I’m not an expert as far as the WordPress database schema is concerned but I’d trust my own database with the knowledge I gathered. As far as I understand it, if your table prefix is wp_254_, then:

      wp_254_comments will contain the comments themselves.

      wp_254_commentmeta will contain any supplementary metadata that things like plugins might have attached to those comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution under the same terms as the associated post.

All comments are moderated. If your comment is generic enough to apply to any post, it will be assumed to be spam. Borderline comments will have their URL field erased before being approved.