Skip to content

Instantly share code, notes, and snippets.

@lichtmetzger
Created February 7, 2023 14:41
Show Gist options
  • Save lichtmetzger/14cd5c03acc13c27eec52cfac79b9288 to your computer and use it in GitHub Desktop.
Save lichtmetzger/14cd5c03acc13c27eec52cfac79b9288 to your computer and use it in GitHub Desktop.
Copy all taxonomy terms into a new taxonomy and re-set them on all posts
<?php
function convert_tax($post_type, $old_tax, $new_tax) {
$pages = get_posts(array(
'post_type' => $post_type,
// Get all post statuses
'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash'),
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $old_tax,
'operator' => 'EXISTS'
)
)
));
foreach($pages as $post) {
$terms = get_the_terms( $post->ID, $old_tax );
$new_terms = array();
foreach( $terms as $t ) {
$new_terms[] = $t->slug;
if( get_term_by( 'slug', $t->slug, $new_tax ) == false ) {
// Clones the terms into the new taxonomy
// Added slug parameter to account for name and slug being different
wp_insert_term( $t->name, $new_tax, $args = array('slug' => $t->slug) );
}
}
// Re-sets previously set terms
wp_set_object_terms( $post->ID, $new_terms, $new_tax );
}
}
convert_tax('company', 'keywords', 'topics');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment