0

I have over 1000 posts. Each post has a custom field XYZ. I'm looking for a function that I can run once that will assign a value of 1 to each of the posts' custom field XYZ. I've had a look at this but i'm not getting how to put it into a one-time-run function?

  • Do you want a free piece of code? Or you want us to help you when you show your pain? Just a bit of code. – Max Yudin Jun 18 '17 at 15:59
6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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