WordPress: Copy taxonomies from one post to another

July 18, 2012

Here is the issue at hand, I have a post with several taxonomies associated with it that may or may not change. I need to dynamically create new posts from said existing post with all the included taxonomies. Copying a post is as easy as getting the existing post from the database and calling wp_insert_post() right after, but doing the same with taxonomies is a whole new ballgame. Here are the steps it takes:

  • Get the post type for the post to copy the taxonomies from
  • Get a list of taxonomies assigned to that post type
  • Loop through the list of taxonomies and request the terms for the existing post per taxonomy
  • Loop through the terms and add the terms to the new post

The code to accomplish this is:

$taxonomies = get_object_taxonomies( get_post_type( $existing_post_id ) );
foreach( $taxonomies AS $tax ) {
    $terms = wp_get_object_terms( $existing_post_id, $tax );
    $term = array();
    foreach( $terms AS $t ) {
        $term[] = $t->slug;
    wp_set_object_terms( $new_post_id, $term, $tax );