Assign/update the custom field value for all posts

You can run a loop through all your posts and change their meta value. To do so, create a plugin and run a loop upon its activation, using get_posts():

<?php
/*
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' );
    }
}
?>

Save this code into a PHP file and upload it to your plugins directory. Once you activate the plugin, this code will run once. Then you can disable or remove it. However, leaving this plugin installed doesn’t do anything, since it only runs on activation.

You no like plugins? No worries!

If you don’t want to use it as a plugin, there’s still a way to do it. One can simply hook into an action that runs after WordPress is loaded, and run your function then:

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' );
    }
}
// Hook into init action and run our function
add_action('init','update_my_metadata');

But notice, you have to remove the code after you load WordPress once. Otherwise, it will run over and over on each load.

Leave a Comment

error code: 523