Taxonomy is a way to group things together. In WordPress we have three taxonomies Category , Tags and Link Categories. If we are writing custom post types we need to add a custom taxonomies to associate with them. Recently I wrote an article with downloadable snippet on how to create a custom post type, so if you don’t know what custom post types are, just go through Custom Post type tutorial first. Now lets move on to custom taxonomies creation with register_taxonomy(); function.
You can add this code into your functions.php file and it will generate a custom taxonomy (like categories in posts) and add custom taxonomy to portfolio and post.
<?php if ( ! function_exists( 'portfolio_taxonomy' ) ) { // Register Custom Taxonomy function portfolio_taxonomy() { $labels = array( 'name' => _x( 'Portfolio Categories', 'Taxonomy General Name', 'text_domain' ), 'singular_name' => _x( 'Portfolio Category', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' => __( 'Category', 'text_domain' ), 'all_items' => __( 'All Items', 'text_domain' ), 'parent_item' => __( 'Parent Item', 'text_domain' ), 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ), 'new_item_name' => __( 'New Item Name', 'text_domain' ), 'add_new_item' => __( 'Add New Item', 'text_domain' ), 'edit_item' => __( 'Edit Item', 'text_domain' ), 'update_item' => __( 'Update Item', 'text_domain' ), 'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ), 'search_items' => __( 'Search Items', 'text_domain' ), 'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ), 'choose_from_most_used' => __( 'Choose from the most used items', 'text_domain' ), 'not_found' => __( 'Not Found', 'text_domain' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, // Is this taxonomy hierarchical (have descendants) like categories or not hierarchical like tags. 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, ); register_taxonomy( 'portfoliocategory', array( 'post', ' portfolio' ), $args ); // this taxonomy will be added to post and portfolio post type. If you want to add this taxonomy to more post types, simple add them to above array separated with a coma. } // Hook into the 'init' action add_action( 'init', 'portfolio_taxonomy', 0 ); } ?>
Calling Custom category on portfolio Single Page with get_the_term_list function
<?php get_the_term_list( $id, $taxonomy, $before, $sep, $after ) ?>
Returns an HTML string of taxonomy terms associated with a post and given taxonomy. Terms are linked to their respective term listing pages.
<?php $pcategory_list = get_the_term_list( $post->ID, 'portfolio_category', '<strong>Portfolio Categories :</strong> ', ', ', '' ); ?> <?php echo $pcategory_list; ?>