|
<?php |
|
/** |
|
* Function to copy tags associated with custom post type to the new custom taxonomy "tag-recurso-educativo". |
|
*/ |
|
function copy_custom_post_type_tags() { |
|
// Set arguments to retrieve custom post type posts. |
|
$args = array( |
|
'post_type' => 'recursos-educativos', // Replace 'recursos-educativos' with your custom post type name. |
|
'posts_per_page' => -1, |
|
); |
|
|
|
// Retrieve custom post type posts. |
|
$custom_posts = new WP_Query($args); |
|
|
|
// Check if there are custom post type posts. |
|
if ($custom_posts->have_posts()) { |
|
// Loop through custom post type posts. |
|
while ($custom_posts->have_posts()) { |
|
$custom_posts->the_post(); |
|
|
|
// Get all tags associated with the post. |
|
$post_tags = get_the_tags(); |
|
|
|
// Check if the post has associated tags. |
|
if ($post_tags) { |
|
// Initialize an array to store the term IDs to be assigned. |
|
$term_ids = array(); |
|
|
|
// Loop through the tags associated with the post. |
|
foreach ($post_tags as $tag) { |
|
// Check if the tag already exists in the new taxonomy. |
|
$existing_term = term_exists($tag->name, 'tag-recurso-educativo'); |
|
|
|
// If the term does not exist in the new taxonomy, create it. |
|
if (!$existing_term) { |
|
$args = array( |
|
'description' => $tag->description, |
|
'slug' => $tag->slug, |
|
); |
|
$inserted_term = wp_insert_term($tag->name, 'tag-recurso-educativo', $args); |
|
|
|
// Check if there was an error inserting the term. |
|
if (is_wp_error($inserted_term)) { |
|
error_log('Error inserting term ' . $tag->name . ' in the new taxonomy: ' . $inserted_term->get_error_message()); |
|
continue; // Skip to the next iteration of the loop in case of an error. |
|
} else { |
|
$term_id = $inserted_term['term_id']; |
|
} |
|
} else { |
|
if (is_array($existing_term)) { |
|
$term_id = $existing_term['term_id']; |
|
} else { |
|
$term_id = $existing_term; |
|
} |
|
} |
|
|
|
// Add the term ID to the array. |
|
$term_ids[] = (int) $term_id; |
|
} |
|
|
|
// Assign the new taxonomy terms to the post. |
|
wp_set_post_terms(get_the_ID(), $term_ids, 'tag-recurso-educativo', false); // Use false to replace existing terms. |
|
} |
|
} |
|
wp_reset_postdata(); // Restore post data. |
|
} |
|
} |
|
add_action('init', 'copy_custom_post_type_tags', 999); |