Converting a Category to a Taxonomy in WordPress

Comments

Here is some code to create a new taxonomy term for each post of a given category.

Taxonomies, post formats, post types… oh my!!

WordPress is beginning to smell more and more of Drupal with every release - at the time of writing you have post categories, post tags, post taxonomies, post types, the pointless post formats (created because ’people were using post types wrong’ apparently). No doubt in the next releases we can expect post flavours, post genres, post breeds, post ilks… but I digress.

First step: create a taxonomy

Still taxonomies and post types are very useful, but sadly there isn’t an easy way to convert from categories or tags to them. Here’s a little bit of code to help. It assumes you have already created your taxonomy - if you don’t know how, check out Justin Tadlock’s excellent tutorials to find out how.

Code snippet to convert categories to a taxonomy

Once you have a taxonomy, put the code below in your functions.php. Amend the variables as required ($gt_taxonomy would be the name of your taxonomy, and $gt_cat you can find out by looking at the link in the Admin > Posts > Categories page). Load any page or admin screen, once, and it should do the job.

Comment out the last line, gt_catToTaxonomyConversion, and have a look at your taxonomy in WordPress to see whether everything went ok. If it did, you can now delete the code from function.php, and delete the category manually. If not, you have to manually delete any newly created taxonomy term, fix the code, and try again. Let me know if there are any issues with the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function gt_catToTaxonomyConversion()
  #AMEND AS REQUIRED
  $gt_taxonomy   = 'my_taxonomy';
  $gt_cat   = 49;

  //get all posts of category $gt_cat
  $gt_posts  = query_posts( array( 'post_type'=> 'post', 'cat'=> $gt_cat, 'nopaging' => true ) );

  //creaate a new taxonomy for each post
  if( !empty( $gt_posts ) ){
    foreach( $gt_posts as  $gt_post ){

      //create taxonomy term and associate post in one go
      wp_set_object_terms( $gt_post->ID, $gt_post->post_name, $gt_taxonomy, false );

      //wp_set_object_terms doesn't have enough options - need to revisit the term and flesh it out a bit
      $gt_term = get_the_terms( $gt_post->ID, $gt_taxonomy );
      $gt_termId  = $gt_term[0]->term_id;
      if( $gt_termId ) {
          wp_update_term( $gt_termId, $gt_taxonomy, array(
                             'description'    => $gt_post->post_content,
                             'slug' => $gt_post->post_name,
                             'name' => $gt_post->post_title
                             ));
      }
    }
  }
}
//comment this out when you run the function once
gt_catToTaxonomyConversion())

Comments