WordPress tip: Add a custom field to all posts

December 6, 2012 at 7:28 pm

For some reason you sometimes need to add a custom field to all your existing posts. You can do it manually, but if you have lots of posts, the process will take a while. Here is a simple way to add a custom field to all posts quickly and easily.

Simply run the following SQL query on your WordPress database, using the command line client or PhpMyAdmin. This will automatically ad a custom field named MyCustomField to all your existing posts.
Don’t forget to backup your database before using this query.

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'MyCustomField'
AS meta_key 'myvalue AS meta_value
FROM wp_posts WHERE ID NOT IN
(SELECT post_id FROM wp_postmeta WHERE meta_key = 'MyCustomField')
`` AND post_type = 'post';

Thanks to Abhishek for the tip!

Tags: