Convert Post Metadata into Tags (Terms)

Just had to do this, wanted to post it somewhere.

Handy l’il snippet when you want to convert post metadata into proper tags.

/*
 * 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";
  }
}

So whatcha think?

I’d love to hear from you.

Leave a Reply