Create and Add Custom Taxonomy to WordPress Posts

Custom Taxonomies are a great way to organise content and should be added to WordPress via a plugin so if a theme is swapped the taxonomies are maintained. Taxonomies are either hierarchal similar to ‘Categories’ or flat, similar to ‘Tags’.

You can assign custom taxonomies to regular posts as well as custom post types.

Create the plugin header and file in /wp-content/plugins either as a standalone .php file or structured inside a directory.

<?php
/*
Plugin Name: WP Beaches Taxonomies
Plugin URI: http://wpbeaces.com/
Description: WP Beaches Custom Taxonomies
Author: Neil Gee
Version:1
Author URI:https://wpbeaches.com
*/

 

Once you have done this the plugin will appear in the Plugins list, it just needs to be activated, but we need to give it some functionality first.

Next up is to create the function and action to load the custom taxonomy

function themename_custom_taxonomies() {
//code goes here
}

add_action( 'init', 'themename_custom_taxonomies' );

Here the function is declared themename_custom_taxonomies and the action init will execute it – now we just need to populate the function.

function themename_custom_taxonomies() {
	// Coaching Method

	$args = array(
		'hierarchical' => true,
		'labels' => $coach_method,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'coach-method' )
	);
    register_taxonomy( 'coach-method', array( 'post' ), $args );
}
add_action( 'init', 'themename_custom_taxonomies', 0 );

So here we are registering a new taxonomy ‘coach-method‘ and assigning it to all posts, this is defined in the first array with ‘post’, to assign the taxonomy to other custom post types you add them in that array separated by commas like so:

function themename_custom_taxonomies() {
	// Coaching Method

	$args = array(
		'hierarchical' => true,
		'labels' => $coach_method,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'coach-method' )
	);
    register_taxonomy( 'coach-method', array( 'coach_mentor', 'post' ), $args );
}
add_action( 'init', 'themename_custom_taxonomies', 0 );

Here the same taxonomy is assigned to posts as well as a CPT (custom post type) named ‘coach_mentor’. The $args  array declares if the taxonomy is hierarchal, defines the label values (more in a minute on this), makes it visible, queryable and sets the url slug.

Labels

Labels set the names in the backend WP Admin interface, so it is best to use real names of what the taxonomy is rather than the generic defaults, the above array sets the value of labels as $coach_method, so the $coach_method labels need to be defined in another array within the same function.

function themename_custom_taxonomies() {
	// Coaching Method

	$coach_method = array(
		'name' => _x( 'Coach Method', 'taxonomy general name' ),
		'singular_name' => _x( 'Coach Method', 'taxonomy singular name' ),
		'search_items' =>  __( 'Search in Coach Methods' ),
		'all_items' => __( 'All Coach Methods' ),
		'most_used_items' => null,
		'parent_item' => null,
		'parent_item_colon' => null,
		'edit_item' => __( 'Edit Coach Method' ),
		'update_item' => __( 'Update Coach Method' ),
		'add_new_item' => __( 'Add new Coach Method' ),
		'new_item_name' => __( 'New Coach Method' ),
		'menu_name' => __( 'Coach Method' ),
	);
	$args = array(
		'hierarchical' => true,
		'labels' => $coach_method,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'coach-method' )
	);
    register_taxonomy( 'coach-method', array( 'coach_mentor', 'post' ), $args );
}
add_action( 'init', 'themename_custom_taxonomies', 0 );

This will take care of all the labels. Now also add another taxonomy within the same function and set it as a flat structure similar to tags.

function themename_custom_taxonomies() {
	// Coaching Method

	$coach_method = array(
		'name' => _x( 'Coach Method', 'taxonomy general name' ),
		'singular_name' => _x( 'Coach Method', 'taxonomy singular name' ),
		'search_items' =>  __( 'Search in Coach Methods' ),
		'all_items' => __( 'All Coach Methods' ),
		'most_used_items' => null,
		'parent_item' => null,
		'parent_item_colon' => null,
		'edit_item' => __( 'Edit Coach Method' ),
		'update_item' => __( 'Update Coach Method' ),
		'add_new_item' => __( 'Add new Coach Method' ),
		'new_item_name' => __( 'New Coach Method' ),
		'menu_name' => __( 'Coach Method' ),
	);
	$args = array(
		'hierarchical' => true,
		'labels' => $coach_method,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'coach-method' )
	);
    register_taxonomy( 'coach-method', array( 'coach_mentor', 'post' ), $args );

    // Coaching Technique
	$coach_technique = array(
		'name' => _x( 'Coach Technique', 'taxonomy general name' ),
		'singular_name' => _x( 'Coach Technique', 'taxonomy singular name' ),
		'search_items' =>  __( 'Search in Coach Techniques' ),
		'all_items' => __( 'All Coach Techniques' ),
		'most_used_items' => null,
		'parent_item' => null,
		'parent_item_colon' => null,
		'edit_item' => __( 'Edit Coach Technique' ),
		'update_item' => __( 'Update Coach Technique' ),
		'add_new_item' => __( 'Add new Coach Technique' ),
		'new_item_name' => __( 'New Coach Technique' ),
		'menu_name' => __( 'Coach Technique' ),
	);
	$args = array(
		'hierarchical' => false,
		'labels' => $coach_technique,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'coach-technique' )
	);
	register_taxonomy('coach-technique', array( 'coach_mentor' ), $args );
}
add_action( 'init', 'themename_custom_taxonomies', 0 );

The second taxonomy is registering ‘coach-technique’ and is only being assigned to one custom post type, it’s hierarchical value is set to false so it will appear as tags – other than that the format is the same.

taxonomy-custom-post-type-values

New Taxonomy Appears Underneath the Post Types it is assigned to

 

taxonomy-custom-post-type

Taxonomies appear and work the same way as Categories and Tags

Flushing the Permalinks

Once you have set up the Taxonomies you will need to flush the permalinks cache by paying a visit to WP Admin > Settings > Permalinks as otherwise the new Taxonomy urls may not appear.

 

Custom Taxonomy Templates

To create custom templates for the taxonomy, you can target all taxonomy templates by using taxonomy.php  or to get more granular you can target each taxonomy term by naming the templates taxonomy-‘taxonomyterm’.php, just swap out taxonomyterm with the actual term. So in the above example the 2 taxonomies can be targetted with taxonomy-coach-method.php and taxonomy-technique-method.php

Displaying the Custom Taxonomy in WordPress Templates

In the front end templates – this is what we would need to add to your loop to display the custom taxonomy near you existing post meta information.

<?php echo get_the_term_list( $post->ID, 'people', 'People: ', ', ', '' ); ?>

This uses the get_the_term_list function  followed by 5 parameters, the post id which is required, the name of the taxonomy, a before label, a separator and an after label.

<?php get_the_term_list( $id, $taxonomy, $before, $sep, $after ) ?>

 

 

Here is a full gist example that uses both ingredients and recipes as tags and categories, you can just change or remove what you don’t need.

<?php
// Add custom taxonomies
/*
Plugin Name: WP Beaches Taxonomies
Plugin URI: http://wpbeaches.com/
Description: WP Beaches Custom Taxonomies
Author: Neil Gee
Version: 1.1.0
Author URI: http://wpbeaches.com
*/
/*Further reference - https://codex.wordpress.org/Function_Reference/register_taxonomy
This example registers the term 'portfolio_category' as the example term in the Category section and 'portfolio_tag' in the Tag example, you need to replace these with the actual term.
The use of _x in certain vales in the array are for translation issues - https://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context
*/
add_action( 'init', 'themeprefix_taxonomies');
function themeprefix_taxonomies() {
// Hierarchal Taxonomy aka Category style - this example uses portfolio
$labels = array(
'name' => _x( 'Portfolio Category', 'taxonomy general name' ),
'singular_name' => _x( 'Portfolio Category', 'taxonomy singular name' ),
'search_items' => __( 'Search in Portfolios Categories' ),
'all_items' => __( 'All Portfolios Categories' ),
'most_used_items' => null,
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Portfolio Category' ),
'update_item' => __( 'Update Portfolio Category' ),
'add_new_item' => __( 'Add new Portfolio Category' ),
'new_item_name' => __( 'New Portfolio Category' ),
'menu_name' => __( 'Portfolio Category' ),
);
$args = array(
'labels' => $labels,
'public' => true,
'show_in_nav_menus' => true,
'show_ui' => true,
'show_tagcloud' => true,
'hierarchical' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'portfolio-category' ),
);
register_taxonomy( 'portfolio_category', array( 'portfolio', 'menu' ), $args );//add in your CPTS that the Taxonomy is applicable to
// Flat Taxonomy aka Tag like - this example uses portfolio
$labels = array(
'name' => _x( 'Portfolio Tags', 'taxonomy general name' ),
'singular_name' => _x( 'Portfolio Tag', 'taxonomy singular name' ),
'search_items' => __( 'Search in Portfolios Tags' ),
'all_items' => __( 'All Portfolios Tags' ),
'most_used_items' => null,
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Portfolio Tag' ),
'update_item' => __( 'Update Portfolio Tag' ),
'add_new_item' => __( 'Add new Portfolio Tag' ),
'new_item_name' => __( 'New Portfolio Tags' ),
'separate_items_with_commas' => __( 'Separate Portfolios Tags with commas' ),
'choose_from_most_used' => __( 'Choose from the most used Portfolios Tags' ),
'not-found' => __( 'No Portfolios Tags found'),
'menu_name' => __( 'Portfolios Tags' ),
);
$args = array(
'labels' => $labels,
'public' => true,
'show_in_nav_menus' => true,
'show_ui' => true,
'show_tagcloud' => true,
'hierarchical' => false,
'show_admin_column' => true,
'query_var' => true,
'update_count_callback' => '_update_post_term_count',
'rewrite' => array( 'slug' => 'portfolio-tag' ),
);
register_taxonomy( 'portfolio_tags', array( 'portfolio', 'menu' ), $args );//add in your CPTS that the Taxonomy is applicable to this example links it to regular posts and a 'menu' custom post type
}
//Flush the permalinks - ref - https://codex.wordpress.org/Function_Reference/register_post_type#Flushing_Rewrite_on_Activation
function prefix_my_rewrite_flush() {
// First, we "add" the custom taxonomies via the above written function.
// Then we flush the permalinks when the plugin is activated so the new taxonomy archives are readily available.
themeprefix_taxonomies();
// ATTENTION: This is *only* done during plugin activation hook in this example!
// You should *NEVER EVER* do this on every page load!!
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'prefix_my_rewrite_flush' );
register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
view raw custom-taxonomy.php hosted with ❤ by GitHub

Leave a Comment





%d bloggers like this: