How to make custom categories nested

How to make custom categories nested

As an example, let’s review a small piece of code that implements a tree with fruits attached to it. In this case, the 'tree' is our custom taxonomy, and 'fruit' is a custom post type used to define fruits with all their parameters (color, taste, etc. — these are not discussed in this article).

Full code example:

add_action('init', function()
{
	register_post_type('fruit', [
		'labels' => [
			'name' => 'Fruits',
			'singular_name' => 'Fruit',
		],
		'public' => true,
		'show_ui' => true,
		'has_archive' => true,
		'rewrite' => [
			'slug' => 'fruit'
		],
		'query_var' => true,
		'hierarchical' => false,
	]);

	register_taxonomy('tree', ['fruit'], [
		'hierarchical' => true,
		'labels' => [
			'name' => 'Tree',
		],
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => [
			'hierarchical' => false
		],
	]);
});

Before registering a taxonomy, you need to initialize the post type to which the taxonomy terms will be attached. This can be done using the register_post_type function:

register_post_type('fruit', [
	'labels' => [
		'name' => 'Fruits',
		'singular_name' => 'Fruit',
	],
	'public' => true,
	'show_ui' => true,
	'has_archive' => true,
	'rewrite' => [
		'slug' => 'fruit'
	],
	'query_var' => true,
	'hierarchical' => false,
]);

Next, we need to register a taxonomy of type “tree” and attach the “fruit” post type to it. This can be done using the register_taxonomy function:

register_taxonomy('tree', ['fruit'], [
	'hierarchical' => true,
	'labels' => [
		'name' => 'Tree',
	],
	'show_ui' => true,
	'query_var' => true,
	'rewrite' => [
		'hierarchical' => true
	],
]);

The full list of parameters for the register_post_type and register_taxonomy functions can be found in the WP Codex.

Now I want to draw your attention to the ['rewrite']['hierarchical'] key. It is responsible for the link nesting. If ['rewrite']['hierarchical'] is set to true, then the generated URLs will look like this: ‘my-site.com/tree/branch-1/branch-1-1/’.

If ['rewrite']['hierarchical'] is set to false, then the URLs will be flat, without parent slugs: ‘my-site.com/tree/branch-1-1/’.

You also shouldn't confuse the ['rewrite']['hierarchical'] parameter with ['hierarchical']. The latter defines the "type" of the taxonomy, similar to default categories or tags in WordPress posts. If set to true, your custom taxonomy will behave like categories and support nesting (as shown in this example). If set to false, it will behave like tags.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *