Replace a meta key with a new key for a given post

This function is used in WordPress to replace a meta key with a new key for a given post. It follows a simple three-step process: retrieving the meta value associated with the old key, updating the metadata with the new key, and deleting the meta value associated with the old key.

/**
 * Replaces a meta key with a new key for a given post in WordPress.
 *
 * This function retrieves the meta value associated with the old key using the
 * `get_post_meta` function. It then updates the metadata for the post with the new
 * key using the `update_metadata` function, and finally, deletes the meta value
 * associated with the old key using the `delete_post_meta` function.
 *
 * @param int    $post_id   The ID of the post for which the meta key is to be replaced.
 * @param string $old_key   The old meta key to be replaced.
 * @param string $new_key   The new meta key to replace the old key.
 * @param string $meta_type Optional. The type of meta. Default is 'post'.
 */
function replace_meta_key($post_id, $old_key, $new_key, $meta_type = 'post') {
    $meta_value = get_post_meta($post_id, $old_key, true);
    update_metadata($meta_type, $post_id, $new_key, $meta_value);
    delete_post_meta($post_id, $old_key);
}

By using this function, you can easily update the meta keys associated with posts in WordPress, which can be useful for various scenarios, such as data migration or updating meta keys due to changes in your data structure or requirements.