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'

1 Answer 1


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.

  • 1
    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 Commented Feb 10, 2013 at 7:08
  • 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
    Commented Feb 10, 2013 at 19:11
  • Where are you putting this code, just put it in your theme functions.php
    – Wyck
    Commented Feb 10, 2013 at 19:12
  • It's in the functions.php now and no error. I got like 900 posts in category Photography. Should it take some time to add the fields or should it be instant?
    – AKNL
    Commented Feb 10, 2013 at 19:19
  • 1
    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
    Commented Feb 12, 2013 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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