Bulk Renaming Meta Fields


Most of the time when working with meta fields I’ll use Advanced Custom Fields. One place where I don’t use ACF is within CaptainCore CLI where data is stored directly into meta fields using WP-CLI. I recently wanted to rename a bunch of meta fields for better organization. WordPress doesn’t have a built-in way to do that so this is how I handled it.

The following PHP script hunts for certain meta field names using metadata_exists. If found it then creates a new meta field using update_post_meta and then deletes the original meta field with delete_post_meta. This works out nicely as it will also move over empty value records and cleanup the old meta keys/values.

With the following code put into a file named rename-meta-fields.php this can be run over WP-CLI like so wp eval-file rename-meta-fields.php. This can easily be adapted for any other bulk meta field renames by changing the arguments passed to get_posts.

<?php

$arguments = array(
        'post_type'      => 'captcore_website',
        'posts_per_page' => '-1',
        'fields'         => 'ids',
);

$websites = get_posts( $arguments );

foreach ( $websites as $post_id ) {

    echo "Updated meta fields for $post_id\n";

    if ( metadata_exists( 'post', $post_id, "homedir" ) ) {
        update_post_meta( $post_id, "home_directory", get_post_meta( $post_id, "homedir", true ) );
        delete_post_meta( $post_id, "homedir" );
    }

    if ( metadata_exists( 'post', $post_id, "homedir_staging" ) ) {
        update_post_meta( $post_id, "home_directory_staging", get_post_meta( $post_id, "homedir_staging", true ) );
        delete_post_meta( $post_id, "homedir_staging" );
    }

}