WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to bulk add a custom field (category) with value (photography) to all posts in a specific category (photography, with Category ID 5).

I have used the code below to bulk add a custom field to all posts, but how can I narrow this down to a specific category? Anyone?

This is the code I used for all posts:

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT wp_posts.ID, 'category', 'photography'
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
share|improve this question
up vote 1 down vote accepted

You can use WordPress functions to do this and just run it once, a fast example would be.

function wpse_85236_add_photo_field(){

global $post;
$photoquery = new WP_Query('posts_per_page=-1');

while ( $photoquery->have_posts() ) : $photoquery->the_post();

    if ( in_category( 'photography' )) {
    add_post_meta($post->ID, 'category', 'photography', true);

add_action( 'init', 'wpse_85236_add_photo_field' );

Remember to remove the function after it runs because you don't want it to run on every load.

share|improve this answer
Instead of running it through functions, which adds a risk of someone running the code twice by mistake, do it with a onetime php file... Also this plugin comes highly recommended – Moshe Eshel Feb 10 '13 at 7:08
Thanks for fixing it Wyck, going to try it out now! – AKNL Feb 10 '13 at 19:01
Tried it in a php file so I can load it only once, but now it says Call to undefined function add_action() in line 14 – AKNL Feb 10 '13 at 19:11
Where are you putting this code, just put it in your theme functions.php – Wyck Feb 10 '13 at 19:12
The timeouts are likely caused by not having enough ram and/or your php settings, your solution of breaking it into sections is a good one when you have those limitations +1 . – Wyck Feb 12 '13 at 16:38

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.