Skip to content

Instantly share code, notes, and snippets.

@silvaitamar
Created May 22, 2024 07:53
Show Gist options
  • Save silvaitamar/99a129a216f187ad8c5bd91ddba9e3e1 to your computer and use it in GitHub Desktop.
Save silvaitamar/99a129a216f187ad8c5bd91ddba9e3e1 to your computer and use it in GitHub Desktop.
Função para copiar as tags associadas aos posts de um tipo customizado para uma nova taxonomia customizada
<?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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment