Add a hierarchical Level taxonomy to a Course post type

Description: Register a post type course and a hierarchical taxonomy level. Add the terms Beginner and Advanced. Create a course WordPress Basics in the level Beginner, and list the courses of that level with WP_Query.

Hint:

  • register_taxonomy( 'level', 'course', array( 'hierarchical' => true ) ).
  • Use a tax_query for the list.

Solution

<?php
/**
 * Plugin Name: Courses
 */
add_action( 'init', function () {
	register_post_type( 'course', array( 'label' => 'Courses', 'public' => true, 'show_in_rest' => true ) );
	register_taxonomy( 'level', 'course', array( 'label' => 'Levels', 'hierarchical' => true, 'show_in_rest' => true ) );
} );
Terminal output

$ wp plugin activate tc-courses
Plugin 'tc-courses' activated.
Success: Activated 1 of 1 plugins.
$ wp term create level "Beginner" –slug=beginner –porcelain
2
$ wp term create level "Advanced" –slug=advanced –porcelain
3
$ wp post create –post_type=course –post_title="WordPress Basics" –post_status=publish –porcelain
5
$ wp post create –post_type=course –post_title="Plugin Security" –post_status=publish –porcelain
6
$ wp post term add 5 level beginner
Success: Added term.
$ wp post term add 6 level advanced
Success: Added term.

$q = new WP_Query( array(
	'post_type' => 'course',
	'tax_query' => array( array( 'taxonomy' => 'level', 'field' => 'slug', 'terms' => 'beginner' ) ),
) );
foreach ( $q->posts as $p ) {
	echo $p->post_title . "\n";
}
Output

WordPress Basics

How it works

  • A taxonomy is registered for a post type, and its terms are connected to the posts through wp_term_relationships.
  • The tax_query asks only for the posts which have the term beginner.

Read Custom Taxonomies.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.