To set the taxonomy post_tag
to your custom post type, you need to set the taxonomies
parameter in your arguments when registering your post type
taxonomies
(array) (optional) An array of registered taxonomies like
category
orpost_tag
that will be used with this post type. This can be used in lieu of callingregister_taxonomy_for_object_type()
directly. Custom taxonomies still need to be registered withregister_taxonomy()
.Default: no taxonomies
So you would add something like this in your arguments
'taxonomies' => ['post_tag'],
You will now have the tag meta box in your custom post type post page.
If you need to set a specific tag to all posts, you can run a custom query to get all the posts you need to alter, and then use wp_set_object_terms()
on each post to set the specific tag
You can try the following: (Requires PHP 5.4+. Also, backup your database before running this query. You can run this once and remove it)
$args = [
'post_type' => 'book',
'posts_per_page' => -1, // If you need all posts, set according to needs
'fields' => 'ids', // Only get post ID's, very lean query
// Add any other paramaters according to need
];
$q = get_posts( $args );
foreach ( $q as $post ) {
if ( term_exists( 'MY_TAG', 'post_tag' )
&& !has_tag( 'MY TAG', $post )
) // Only run if the tag is not yet assigned and if it exists
wp_set_object_terms(
$post, // Post ID
'MY TAG', // Term to add, tag in this case
'post_tag', // Taxonomy the term belongs to
true // Append the tag, don't replace tags
);
}