Categories
Uncategorized

Day 7: Taxonomies

The main idea here is to create categories to group posts. The taxonomy can be hierarchical or flat. WordPress stores taxonomies in term_taxonomy table allowing developers to register custom taxonomies. Taxonomies have terms by which you can classify things, which are stored in terms table.

E.g. Taxonomy: Art, Terms: modern, classic, medieval,etc.

Categories and tags are the taxonomies provided by wordpress. Following code shows how to add custom taxonomy.

<?php
/*
* Plugin Name: Course Taxonomy
* Description: A short example showing how to add a taxonomy called Course.
* Version: 1.0
* Author: developer.wordpress.org
* Author URI: https://codex.wordpress.org/User:Aternus
*/
 
function wporg_register_taxonomy_course()
{
    $labels = [
        'name'              => _x('Courses', 'taxonomy general name'),
'singular_name'     => _x('Course', 'taxonomy singular name'),
'search_items'      => __('Search Courses'),
'all_items'         => __('All Courses'),
'parent_item'       => __('Parent Course'),
'parent_item_colon' => __('Parent Course:'),
'edit_item'         => __('Edit Course'),
'update_item'       => __('Update Course'),
'add_new_item'      => __('Add New Course'),
'new_item_name'     => __('New Course Name'),
'menu_name'         => __('Course'),
];
$args = [
'hierarchical'      => true, // make it hierarchical (like categories)
'labels'            => $labels,
'show_ui'           => true,
'show_admin_column' => true,
'query_var'         => true,
'rewrite'           => ['slug' => 'course'],
];
register_taxonomy('course', ['post'], $args);
}
add_action('init', 'wporg_register_taxonomy_course');

Take a look at register_taxonomy() function for a full list of accepted parameters and what each of these do.

With our Courses Taxonomy example, WordPress will automatically create an archive page and child pages for the course Taxonomy. The archive page will be at /course/ with child pages spawning under it using the Term’s slug (/course/%%term-slug%%/).

Using the taxonomy

WordPress has many functions for interacting with your Custom Taxonomy and the Terms within it.

Here are some examples:

  • the_terms: Takes a Taxonomy argument and renders the terms in a list.
  • wp_tag_cloud: Takes a Taxonomy argument and renders a tag cloud of the terms.
  • is_taxonomy: Allows you to determine if a given taxonomy exists.

Leave a comment

Design a site like this with WordPress.com
Get started