Sharing a WordPress taxonomy between two post types is useful especially if you want to create a relation between different items of the two post types, but this action may create a few misunderstandings.
Here are some notes.
Suppose you create a post type named news
and you want to use the existing post_tag
taxonomy to tag also the news articles.
To add the post_tag
taxonomy to the news
post type you can write something like this:
function news_reg_tag() {
register_taxonomy_for_object_type('post_tag', 'news');
}
add_action('init', 'news_reg_tag');
Wrong count in WordPress tag list
When you tag a post
(an article of post type post
) with a specific tag and then you tag a news
(an article of post type news
) with the same specific tag, when you will load the “Tags” page in WordPress “Posts” menu, you will see that the count for that specific tag is 2, but if you click on the number 2 you will see only 1 article, the one tagged in the post
post type.
There are no errors. The count is 2, because 1 for post
and 1 for news
.
Extract all the tags (shared between two post types) used with a specific post type
Suppose you have post
articles and news
articles (different post types, both uses post_tag
taxonomy).
To retrieve the list of tags used in post
post type you have to use wp_get_object_terms
and use the posts to get the tags:
$articles_in_post_type = get_posts( array(
'fields' => 'ids',
'post_type' => 'post',
'posts_per_page' => -1,
));
$tags = wp_get_object_terms( $articles_in_post_type, 'post_tag', array('ids') );
If you use the get_tags function, like this:
$tags = get_tags(array(
'hide_empty' => false
));
…it will not work, because it uses also the tag used with the news
articles even if you use the hide_empty
parameter. They will not be considered empty, since they are connected to news
.
You can find more articles about WordPress here.