-
-
Save alispx/6e1fdbd54af9c982a308 to your computer and use it in GitHub Desktop.
A function for converting existing WordPress meta keys to new values.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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