Clean up Out-dated Custom Field Data in WordPress Post

If you ever used a magazine-style theme, you must be familiar with the concept "custom field". In essence, it’s a key-value pair storing post data about what additional info to display in a specific page. In most cases, we take advantage of custom field to display an image related to the post.

Problems We Have

There are two major problems with this.

Firstly, the name of the keys differ among various themes, as a result of which, some custom field data turn to be outmoded when you change the theme.

Secondly, while a post is becoming out-dated as time goes, there’s little chance for that post to be displayed in any page at all. And the custom field data belonging to that post is getting redundant as well.

Solutions We Get

For the first question, the answer is in the following steps:

Step 1: Go to WordPress admin page and edit whichever post contains that custom field key, then write down the name of the key. In the example below, it is "image".

Step 2: Go to you phpMyAdmin page and choose the WordPress database from the left column, then click the SQL query window icon.

Step 3: Type in following query string and "GO". That’s it. (Replace "image" with your key name.)

# remove entries with "image" as key name
DELETE FROM wp_postmeta WHERE meta_key = ‘image’

For the second case, I’ll just provide a way of thinking, instead of a solid answer. For instance, I’ve got five posts with custom fields to show in a specific page, then I should keep the custom fields belonging to the latest five post, and delete the rest of them. A small change of the query string above will do just fine.

# get the latest post_id
SELECT @idMax := MAX(post_id) FROM wp_postmeta;
# keep the latest five and remove the rest of them
DELETE FROM wp_postmeta WHERE (@idMax – post_id > 5) AND meta_key = ‘image’

NOTICE: Use the statements above at your own risk, because the value of post_id does not always increase normally.

作者:Keefe Dunn

a dreamer, a learner, a lawful beginner.

1条评论

  1. Many thanks for your instructions for the first case – just what I needed. Works a treat!

发表评论

您的电子邮箱地址不会被公开。