How to convert custom field value to tag

Since this is a one-time task, it’s easiest to create a migration script like so.

Note: It might timeout (trying to process 90k rows) depending on how much memory your server has.

function my_migration_script() {
  global $wpdb;

  // Quick and dirty way to get post ids. Normally don't use this method.
  $post_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type="post"" );

  // Loop through all ids.
  foreach ( $post_ids as $post_id ) {

    // Grab the location meta value if it exists.
    if ( $value = get_post_meta( $post_id, 'location', true ) ) {

      // Remove any commas since it's used as a delimiter.
      $value = str_replace ( ',', '', $value );

      // Create a tag based on the `location` custom field value.
      wp_add_post_tags( $post_id, $value );
    }
  }

  // Uncomment if you'd rather delete without verifying first.
  // $wpdb->delete( $wpdb->postmeta, array( 'meta_key' => 'location' ) );
}

// Kick off the script.
my_migration_script();

Lastly, delete all the old location custom field values directly from the db (using phpMyAdmin or whatever db access tool you have).

DELETE FROM wp_postmeta WHERE `meta_key` = 'location';

I put this outside of the script so you can first verify the migration was successful, and to save php memory resources during the execution.

If you don’t have phpMyAdmin access, just uncomment the line above in the script and run it again.

Note: If the tag already exists, it won’t duplicate it so you can run the script multiple times without harm.

Leave a Comment