Custom meta field values sometimes need tweaking. Need to convert current post meta in your database? Need to perform a str_replace or preg_replace on a specific custom meta key on your WordPress site?
Here a quick function you can put in your wordpress theme’s functions.php file. Be careful before performing any of these search replaces on your fields!! Be sure you have a backup of your WP database. After saving your functions file, reload an admin dashboard page and your function will run (this function runs on admin_init). You only need to run it once, so be sure to comment it out when you are finished. This function will run on all posts in your current site.
This comma will delete a comma from the meta field _my_customfield
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
add_action('admin_init', 'modifyMetaDB'); function modifyMetaDB(){ // The Query $args = array ( 'posts_per_page' => -1 ); $the_query = new WP_Query( $args ); // The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); $meta_key = '_my_customfield'; $getMeta = get_post_meta( get_the_ID(), $meta_key, true); // this is where you specify how you'd like to modify, here we are removing commas $newMeta = str_replace(array(','), '', $getMeta); //update with the new meta values update_post_meta(get_the_ID(), $meta_key, $newMeta); endwhile; } |