modemlooper avatar
AboutBlog

WordPress Migrate Categories or Tags

•2 min read
wordpressphp

A couple functions that migrated categories or tags.

// Lets create our tags. We will use wp_insert_term hooked to init
function emg_add_cat_to_tags() {
	// Get all categories
	$categories = get_categories( [ 'hide_empty' => 0 ] );

	// Probably totally unnecessary, but check for empty $categories 	if ( ! $categories ) { 		return; 	}

	// Loop through the categories and create our tags 	foreach ( $categories as $category ) { 		// First make sure that there is no tag that exist with the same name 		if ( term_exists( $category->name, 'post_tag' ) ) { 			continue; 		}

		// Set our arguments for our terms from $category 		$args = [ 			'description' => $category->description, 			'parent'      => 0, // We can drop this, default is 0 			'slug'        => $category->slug, 		]; 		wp_insert_term( $category->name, 'post_tag', $args ); 	} } add_action( 'init', 'emg_add_cat_to_tags' );

function emg_add_tags_to_post() { 	// Get all our posts 	$args = [ 		'posts_per_page' => -1, 		'fields'         => 'ids', // Make the query lean 		// Add any additional query args here 	]; 	$q = new WP_Query( $args );

	if ( ! $q->have_posts() ) { 		return; 	}

	while ( $q->have_posts() ) { 		$q->the_post();

		// Get all the categories attached to the post 		$categories = get_the_category(); 		if ( ! $categories ) { 			continue; 		}

		// Get the names from the categories into an array 		$names = wp_list_pluck( $categories, 'name' ); 		// Loop through the names and make sure that the post does not already has the tag attached 		foreach ( $names as $key => $name ) { 			if ( has_tag( $name ) ) { 				unset( $names[ $key ] ); 			} 		} 		// Make sure we still have a valid $names array 		if ( ! $names ) { 			continue; 		}

		// Finally, attach our tags to the posts
		wp_set_post_terms(
			get_the_ID(), // Post ID
			$names, // Array of tag names to attach
			'post_tag',
			true // Only add the tags, do not override
		);
	}
	wp_reset_postdata();
}
add_action( 'template_redirect', 'emg_add_tags_to_post' );