I mean; There are more than 7000 posts. some have private space but some do not. I want to add a custom field in bulk to those that do not contain custom fields and update their values.

The following plugin codes have been created to update the meta values of all posts. I just want to add it to posts that do not contain meta values. how can I do that?

Plugin Name: Update MetaData for Posts
Description: Enable this plugin to update the metadata for all the posts
Author: JackJohansson
Version: 1.0
Author URI: http://example.com
// Run the loop when the plugin is activated
register_activation_hook(__FILE__, 'update_my_metadata');
function update_my_metadata(){
    $args = array(
        'post_type' => 'post', // Only get the posts
        'post_status' => 'publish', // Only the posts that are published
        'posts_per_page'   => -1 // Get every post
    $posts = get_posts($args);
    foreach ( $posts as $post ) {
        // Run a loop and update every meta data
        update_post_meta( $post->ID, 'meta-key', 'meta_value' );

1 Answer 1


You can use meta_query parameter (and Query all posts where a meta key does not exist) to limit the query to only posts that have or don't have a certain meta value.

$query = new WP_Query(array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'meta_query' => array(
            'key' => 'your_meta_key',
            'compare' => 'NOT EXISTS',
    'no_found_rows' => true,
    'fields' => 'ids',

if ( $query->posts ) {
        function($post_id, $index) {
            update_post_meta( $post_id, 'your_meta_key', 'meta_value' );

Also, depending on your hosting, you may want to set a limit to the posts_per_page and run the script multiple times (cronjob maybe?) instead of using -1 as the query for thousands of posts might crash the site or the execution time could run out.

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.