Skip to content

Instantly share code, notes, and snippets.

@alispx
Forked from ChaseWiseman/convert-post-meta.php
Created December 27, 2015 09:50
Show Gist options
  • Save alispx/6e1fdbd54af9c982a308 to your computer and use it in GitHub Desktop.
Save alispx/6e1fdbd54af9c982a308 to your computer and use it in GitHub Desktop.
A function for converting existing WordPress meta keys to new values.
/**
* Convert existing meta keys to new meta keys.
*
* @since x.x.x
*
* @global object $wpdb The current database.
*
* @param string $existing_key The existing meta key.
* @param string $new_key The new meta key.
* @param bool $remove_existing Optional. Whether to remove the old meta entries after conversion.
* @return bool Whether any meta keys were converted.
*/
function convert_post_meta( $existing_key, $new_key, $remove_existing = false ) {
global $wpdb;
$existing_metas = $wpdb->get_results( $wpdb->prepare(
"
SELECT value.meta_value, value.post_id
FROM $wpdb->postmeta value
WHERE value.meta_key = '%s'
",
$existing_key
), ARRAY_A );
if ( ! empty( $existing_metas ) ) {
foreach ( $existing_metas as $existing_meta ) {
add_post_meta( $existing_meta['post_id'], $new_key, $existing_meta['meta_value'] );
}
if ( $remove_existing ) {
delete_post_meta( $existing_meta['post_id'], $existing_key );
}
return true;
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment