Add custom field to all posts in specific category

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?

Read More

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'

Related posts

Leave a Reply

1 comment

  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);
        }
    
    endwhile;
    }
    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.