Convert Post Metadata into Tags (Terms)

There are times when you need to re-organize how your WordPress post data is saved. In my case, I recently wanted to change some metadata into an actual term relationship for a number of posts. This snippet took all of my `vendor` posts, which had post metadata `vendor_markets` and `vendor_category`, and properly categorized them.

Now, some notes:

  1. This is definitely rough code, and you’d need to refine for your own purposes.
  2. This should be run on a specific template page just once.
  3. BACKUP before you use something like this!
  4. I’d recommend commenting out parts like `wp_set_post_terms` until you confirm it’s working the way you want it to.

All righty then…

/*
 * Convert all vendors' post metadata for markets and categories
 * to taxonomic relationship
 */
$query = new WP_Query(
  array( 
    'post_type' => array('vendor'),
    'posts_per_page' => -1, // get all vendors
    'orderby'   => 'meta_value_num',
    'order'			=> 'DESC',
  ) 
);


if ( $query->have_posts() ) {
  while( $query->have_posts() ) {
    $query->the_post();

    $id = get_the_ID();
    $markets = get_post_meta( $id, 'vendor_markets', true );
    $category = get_post_meta( $id, 'vendor_category', true );

    echo $id . ' ' . get_the_title() . ' ' . implode('|', $markets) . ' ' . implode('|', $category);
  
    if( ! empty( $markets ) ) {
      $markets = array_map( 'intval', $markets );
      wp_set_post_terms( $id, $markets, 'market' );
    }

    if( ! empty( $category ) ) {
      $category = array_map( 'intval', $category );
      wp_set_post_terms( $id, $category, 'offering' );
    }
    echo "\n";
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *