Created
October 30, 2024 18:23
-
-
Save joychetry/955e503a1c0fdf05c6a699e5069a14dd to your computer and use it in GitHub Desktop.
Copy Taxonomy Data WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define your source and target taxonomies, as well as the post type (optional) | |
$source_taxonomy = 'project-category'; // Source taxonomy | |
$target_taxonomy = 'project-tag'; // Target taxonomy | |
$post_type = 'project'; // Replace with your post type, or leave empty for all | |
// Function to copy terms from the source taxonomy to the target taxonomy | |
function copy_taxonomy_terms( $source_taxonomy, $target_taxonomy, $post_type = '' ) { | |
// Step 1: Get all posts in the specified post type with terms from the source taxonomy | |
$args = array( | |
'post_type' => $post_type ?: 'any', // Use 'any' for all post types if not specified | |
'posts_per_page' => -1, | |
'post_status' => 'any', | |
'tax_query' => array( | |
array( | |
'taxonomy' => $source_taxonomy, | |
'field' => 'slug', | |
'terms' => get_terms(array('taxonomy' => $source_taxonomy, 'fields' => 'slugs')), | |
'operator' => 'IN', | |
), | |
), | |
); | |
$posts = get_posts( $args ); | |
// Step 2: Loop through each post to copy terms to the target taxonomy | |
foreach ( $posts as $post ) { | |
// Get the source terms for the current post | |
$source_terms = wp_get_post_terms( $post->ID, $source_taxonomy, array( 'fields' => 'slugs' ) ); | |
if ( ! empty( $source_terms ) ) { | |
// Step 3: Check if each term exists in the target taxonomy, and create if it doesn't | |
foreach ( $source_terms as $term_slug ) { | |
if ( ! term_exists( $term_slug, $target_taxonomy ) ) { | |
// If term does not exist, create it in the target taxonomy | |
$term = get_term_by( 'slug', $term_slug, $source_taxonomy ); | |
wp_insert_term( $term->name, $target_taxonomy, array( 'slug' => $term_slug ) ); | |
} | |
} | |
// Step 4: Assign the terms to the target taxonomy for the post | |
wp_set_post_terms( $post->ID, $source_terms, $target_taxonomy, false ); | |
} | |
} | |
} | |
// Run the function on 'init' - Remember to remove this after running once | |
add_action( 'init', function() use ( $source_taxonomy, $target_taxonomy, $post_type ) { | |
copy_taxonomy_terms( $source_taxonomy, $target_taxonomy, $post_type ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment