44

I have a custom post type called portfolio and I'm trying to add the tags taxonomy to it, how do I do this?

2
  • @chifliiiii if I do that, the Categories and Tags are the same as the ones used for Posts. How do I get Categories and Tags that are exclusive to the new post type? May 8, 2014 at 16:36
  • @chifliiiii As display the tags in the template?
    – Max
    Mar 21, 2017 at 23:54

9 Answers 9

26

Like this: (Where it says "portfolio" is where you register the taxonomy to a post type

add_action( 'init', 'create_tag_taxonomies', 0 );

//create two taxonomies, genres and tags for the post type "tag"
function create_tag_taxonomies() 
{
  // Add new taxonomy, NOT hierarchical (like tags)
  $labels = array(
    'name' => _x( 'Tags', 'taxonomy general name' ),
    'singular_name' => _x( 'Tag', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Tags' ),
    'popular_items' => __( 'Popular Tags' ),
    'all_items' => __( 'All Tags' ),
    'parent_item' => null,
    'parent_item_colon' => null,
    'edit_item' => __( 'Edit Tag' ), 
    'update_item' => __( 'Update Tag' ),
    'add_new_item' => __( 'Add New Tag' ),
    'new_item_name' => __( 'New Tag Name' ),
    'separate_items_with_commas' => __( 'Separate tags with commas' ),
    'add_or_remove_items' => __( 'Add or remove tags' ),
    'choose_from_most_used' => __( 'Choose from the most used tags' ),
    'menu_name' => __( 'Tags' ),
  ); 

  register_taxonomy('tag','portfolio',array(
    'hierarchical' => false,
    'labels' => $labels,
    'show_ui' => true,
    'update_count_callback' => '_update_post_term_count',
    'query_var' => true,
    'rewrite' => array( 'slug' => 'tag' ),
  ));
}
?>
7
  • @JoeBobby it would probably be worth checking out the WordPress Codex page for registering taxonomies to get a better feeling for all of the available options: codex.wordpress.org/Function_Reference/register_taxonomy
    – Stephen S.
    May 8, 2014 at 16:41
  • 13
    Just a note that this is creating a whole new taxonomy called 'tag' instead of adding the existing 'post_tag' taxonomy to the custom post type.
    – Jake
    Jun 28, 2017 at 17:53
  • @chifliiiii how to get these tags in post single page with tags links, how to create a template for tag page
    – Dinesh
    Jun 25, 2018 at 9:05
  • 1
    I agree with Jake, I feel like this does not solve the problem. @Marcus' answer should be the one marked as accepted. Jul 12, 2018 at 21:20
  • how to access the template for this 'tag' taxonomy? What is the name of the template?
    – emir
    Jun 8, 2021 at 8:04
98

Or just add:

'taxonomies' => array('post_tag')

An array of registered taxonomies like category or post_tag that will be used with this post type. This can be used in lieu of calling register_taxonomy_for_object_type() directly. Custom taxonomies still need to be registered with register_taxonomy().

to the $args array in the functions.php-file where you create the custom post type with register_post_type(). This will add a custom post type to use the same categories and/or tags as built-in posts.

1
  • 3
    Please add an explanation to your answer: why could that solve the problem?
    – fuxia
    Jul 12, 2013 at 3:54
10

Use this:

add_action( 'init', 'gp_register_taxonomy_for_object_type' );
function gp_register_taxonomy_for_object_type() {
    register_taxonomy_for_object_type( 'post_tag', 'portfolio' );
};
2

Method 1 (from answers above: https://wordpress.stackexchange.com/a/106211/38771)

Different post types will use the same "Tags" data of the default "post" type.

  • Benefits

    • Everything (should) works out of the box with one line

    • All your tags in one place in the CMS

  • Downsides

    • Forget about a well structured / easy to use CMS - the Tags listing on the custom post types page will show all Tags (not just the tags used in the custom post type articles) with the wrong count ...
    • Changes to a Tag will affect the default "post" articles as well as the custom post type articles (Delete a Tag deletes it in both types of articles)
    • Harder (possibly impossible) to setup any distinct Tag functionality: different descriptions, custom fields, images, etc (at least not without much custom coding on top of core Wordpress code)...

Method 2 (from answers above: https://wordpress.stackexchange.com/a/62263/38771)

Different post types use different "Tags" configuration / data.

  • Benefits

    • Create different/clearly distinct tag-related functionality: frontend templates, capabilities, query filters, actions)
    • Assign different tag related data: fields data or even custom fields
    • Manage Tags better in CMS
      • Example: Editing/Delete a "post" tag won't affect the (similarily named/slugged) tag for the other post types
  • Tradeoff

    A bit more code to setup

In truth, they are an extremely powerful way to group various items in all sorts of ways. https://codex.wordpress.org/Taxonomies#Custom_Taxonomies

4
  • Here's a case for Method 1: A large sports website, covering numerous topics/leagues/sports with tags e.g. "NBA", "NHL", "Basketball", "Olympics", "Steroids", "College", etc It doesn't make any sense to duplicate, and manage, what could be +100 tags and 4 post types (default post type and 3 custom post types). As for the downsides, if tag count data is so special, then a custom view can be made for that. As for similar custom tags per post type, there doesn't seem to be any obvious need as of yet (trying hard to think of one... need examples).
    – Kalnode
    Jan 12, 2019 at 0:23
  • Yes but there won't automatically be different tag permalinks for different post types. A tag "playoffs" will have "/tag/playoffs" for all post types. Then you have to setup rewrite rules or use GET params to create different permalinks... With a different taxonomy for every post type, every "playoffs" tag for every post type will have its own permalink, that can be customized using Wordpress' Template Hierarchy. That's good if different "playoffs" pages are different for NBA, NHL... I worked on a site with that level of customization for taxonomies (custom fields, taxonomy image, description)
    – P-S
    Jan 14, 2019 at 13:53
  • 1
    I see what you're saying. So, if going with different tag taxonomies per CPT, how about making it so when you add/edit a term in one tax, it gets changed in other tax's ie synchronized unique terms across tax's. e.g. define "Basketball" once, let's say in Post tags tax, then once you hit save, then "Basketball" also gets uniquely created across other tax's for CPT's. So input/edit a tag once, and the change is reflected across multiple tag tax's. In the end you get tag management in one destination, plus more desirable permalink situation.
    – Kalnode
    Jan 15, 2019 at 1:15
  • Yea that would actually be a great method if the site shares the same basic taxonomies information (title) for multiple CPTs, as well as giving the option to further customize these taxonomies (custom fields, images, etc) for different CPT. Nice!
    – P-S
    Jan 18, 2019 at 11:44
1

Just use this code may be it help you

 add_action( 'init', 'create_client_tax' );
function create_client_tax() {
    register_taxonomy( 
            'client_tag', //your tags taxonomy
            'client',  // Your post type
            array( 
                'hierarchical'  => false, 
                'label'         => __( 'Tags', CURRENT_THEME ), 
                'singular_name' => __( 'Tag', CURRENT_THEME ), 
                'rewrite'       => true, 
                'query_var'     => true 
            )  
        );
}
1
  • A stripped version of the accepted already answer. Also, this also adds a whole new taxonomy rather than using the existing 'post_tag' taxonomy.
    – acidrums4
    Jul 11, 2018 at 17:36
1

This always works fine. ref: https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/

/**
* Create taxonomies tag for CPT portfolio
*/
if ( ! function_exists( 'ns_register_team_category' ) ) {
function ns_register_team_category() {

   $labels = array(
    'name' => __( 'Tags', 'ns' ),
    'singular_name' => __( 'Tag', 'ns' ),
    'search_items' =>  __( 'Search Tags' ),
    'popular_items' => __( 'Popular Tags' ),
    'all_items' => __( 'All Tags' ),
    'parent_item' => null,
    'parent_item_colon' => null,
    'edit_item' => __( 'Edit Tag' ),
    'update_item' => __( 'Update Tag' ),
    'add_new_item' => __( 'Add New Tag' ),
    'new_item_name' => __( 'New Tag Name' ),
    'separate_items_with_commas' => __( 'Separate tags with commas' ),
    'add_or_remove_items' => __( 'Add or remove tags' ),
    'choose_from_most_used' => __( 'Choose from the most used tags' ),
    'menu_name' => __( 'Tags' ),
   );

   $args = array(
    'label' => __( 'Tag', 'ns' ),
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'hierarchical' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => 'tag', 'with_front' => false, ),
    'show_admin_column' => false,
    'show_in_rest' => true,
    'rest_base' => 'tag',
    'rest_controller_class' => 'WP_REST_Terms_Controller',
    'show_in_quick_edit' => true,
    'update_count_callback' => '_update_post_term_count',
);
register_taxonomy( 'tag', array( 'portfolio' ), $args );
}
add_action( 'init', 'ns_register_team_category', 0 );
}
1

You can just add an already registered taxonomy to an object type, see the code below.

 /**
 * Function to add Tag Selection to Custom Post Type
 */
 function ns_reg_tag() {
    register_taxonomy_for_object_type('post_tag', 'Custom_Post_Type');
 }
add_action('init', 'ns_reg_tag');
1
  • This is the best solution currently. Apr 6, 2022 at 0:21
0

Although the answer of Marcus solves the majority of the problem, be aware that it is not a complete solution. The answer of chifliiiii is more complete but like mentioned in the comments it's not reusing the already existing tags taxonomy.

According to the OP, a solution must use "the tag taxonomy" and not "a tag taxonomy". Thus that's why I think the answer of chifliiiii is incorrect.

On the other hand I think the answer of Marcus is partly correct, the same goes for similar answers like the one Giovanni Putignano posted. I will explain below why.


A complete solution

By registering your custom post type to the post_tag taxonomy, using either the method Marcus or Giovanni is suggesting, will not display tagged posts of your custom post type on the tag's archive page. It will only display posts of the post post type, because the built-in tag template is rendered with a query what only targets the post post type. To fix this you need to alter the query with the pre_get_posts hook.

This is a generic way to solve this (don't ask me why this isn't implemented in the core):

add_action('pre_get_posts', function($query) {
  // This will target the queries used to generate the tag archive template.
  // You may remove the `is_main_query()` condition if you want to get posts
  // by tag outside the loop.
  if (!is_admin() && is_tag() && $query->is_main_query()) {
    // Will set to something like: Array( 'post', 'portfolio' )
    $types = get_taxonomy('post_tag')->object_type;

    // Alter the query to only use the types which are registered to the
    // `post_tag` taxonomy.
    $query->set('post_type', $types);
  }
});
0

In my case following code is worked.

register_taxonomy( 'events_tag',array('events'),  array(
        'hierarchical' => false, 
        'label' => 'Tag',
        'show_admin_column' => true, 
        'singular_label' => 'Your Post type Tag',
        'query_var'         => true,
        'rewrite' => array( 'slug' => 'events_tag' ),
        'show_in_rest'       => true,
        'rest_base'          => 'events_tag',
        'rest_controller_class' => 'WP_REST_Terms_Controller',  
        )
    );

Not the answer you're looking for? Browse other questions tagged or ask your own question.