As we have seen, posts always appear in collections. There’s often the need to create sub-collections out of this main collection. This is where taxonomies come in.
Flat vs. Hierarchical Taxonomies
Taxonomies can be divided into main types: hierarchical taxonomies and flat taxonomies. Which one to use depends a lot on the individual scenario.
Imagine that you have news articles related cities and states/provinces. Your news article relates to a particular city and State/Province. Therefore a straightforward approach might be to have a single taxonomy with parent terms representing the States/Provinces, and child terms for the individual cities. With this approach, it would be easy to list all the news in a particular place.
As for the flat taxonomies, imagine that you have a post type for videos. You want to be able to tag these videos with the names of the people appearing in them. In this case, a flat taxonomy would be the best approach.
For clarification purposes, taxonomies and terms are two different things. Terms are each individual item within a taxonomy. For example, “New York” is a term within the “Locations” taxonomy.
Creating Taxonomies
There are two ways you can create taxonomies. You can either add the register_taxonomy() to the post type plugin in case the taxonomy and the post type are related, or you can create a separate plugin for the taxonomy in case multiple post types will share it.
Please remember to replace PREFIX with your own project prefix and replace textdomain with your own text domain.
<?php
/**
* Plugin Name: PREFIX Taxonomies - Locations
* Plugin URI: http://trewknowledge.com/
* Description: A plugin to register the Locations taxonomy.
* Version: 1.0.0
* Author: Trew Knowledge
* Author URI: http://trewknowledge.com/
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: textdomain
*/
add_action( 'init', function() {
/*
Load Load Translations
*/
load_plugin_textdomain( 'textdomain', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
/*
Register Locations Taxonomy
*/
$labels = array(
'name' => _x( 'Themes', 'taxonomy general name', 'textdomain' ),
'singular_name' => _x( 'Theme', 'taxonomy singular name', 'textdomain' ),
'search_items' => __( 'Search Themes', 'textdomain' ),
'all_items' => __( 'All Themes', 'textdomain' ),
'parent_item' => __( 'Parent Theme', 'textdomain' ),
'parent_item_colon' => __( 'Parent Theme:', 'textdomain' ),
'edit_item' => __( 'Edit Theme', 'textdomain' ),
'update_item' => __( 'Update Theme', 'textdomain' ),
'add_new_item' => __( 'Add New Theme', 'textdomain' ),
'new_item_name' => __( 'New Theme Name', 'textdomain' ),
'menu_name' => __( 'Theme', 'textdomain' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'locations' ),
'show_in_rest' => true,
);
register_taxonomy( 'prefix_tax_location', array( 'prefix_post_type' ), $args );
} );