The Taxonomy
class, as the name suggests, helps you build custom taxonomies.
In order to register a custom taxonomy, you will call the make
and set
methods of the Taxonomy class.
For example, let's register a custom taxonomy in order to handle a list of authors for our books custom post type from previous examples. The custom taxonomy will have a slug of authors
:
Taxonomy::make('authors', 'books', 'Authors', 'Author')->set([
'public' => true
]);
This will build a basic custom taxonomy accessible from the books custom post type. You can customize your taxonomy by passing arguments to the set()
method. In the above code we specified that the custom taxonomy should be public. You can pass all the arguments defined in the WordPress core function register_taxonomy like so:
Taxonomy::make('authors', 'books', 'Authors', 'Author')->set([
'public' => true,
'rewrite' => false,
'query_var' => false,
'hierarchical' => true
]);
Note: the custom taxonomy is only registered if you call the
set()
method.
The make()
method needs a plural and singular display names as third and fourth parameter. Those parameters will pre-fill the labels property of your custom taxonomy.
Taxonomy::make('authors', 'books', 'Authors', 'Author')->set();
In the above code sample, the custom taxonomy will have a plural display name of Authors
and a singular display name of Author
.
Note: you can override the custom taxonomy
labels
property by adding it to the set method array.
In order to define the behavior of your custom taxonomy, use the set()
method and pass it an array of arguments like so:
Taxonomy::make('authors', 'books', 'Authors', 'Author')->set([
'public' => true,
'show_in_nav_menus' => false,
'hierarchical' => true,
'show_tagcloud' => false,
'show_in_quick_edit' => false
]);
You can define a taxonomy that can be shared between multiple post types by passing an array of post type names like so:
Taxonomy::make('authors', ['post', 'books'], 'Authors', 'Author')->set();
The above code register an authors
taxonomy for both post
and books
post types.
Attach the post type to the taxonomy inside filter callback that run during parse_request
or pre_get_posts
.
You can use the bind()
method which is a shortcut to the register_taxonomy_for_object_type function.
Call the method on your taxonomy instance like so:
$tax = Taxonomy::make('authors', ['post', 'books'], 'Authors', 'Author')->set();
// Bind the taxonomy to the 'post' and 'books' post types.
$tax->bind();
You can also bind your taxonomy when registering your custom post type by adding the
taxonomies
argument. Check the register_post_type function.
Made in Belgium