How to Attach an Existing Taxonomy to a New Post Type in WordPress

How to Attach an Existing Taxonomy to a New Post Type in WordPress

When working on third-party plugins or a purchased theme, we may encounter a situation where we need to attach an existing taxonomy (created by someone else) to a custom post type we’ve created (in our case, “fruits” — see this article).

There are two ways to solve this:

  1. You can edit the existing code directly. But that’s not ideal, because any updates to the plugin or theme will overwrite your changes, and you’ll have to reapply them (if you remember to).
  2. Use WordPress Hooks and Filters to apply your modifications safely.

In the short example below, you’ll find all the code you need:

add_action('init', function()
{
	register_taxonomy_for_object_type('tree', 'fruit');
});

add_filter('register_taxonomy_args', function($args, $taxonomy)
{
	if($taxonomy == 'tree')
	{
		$args['show_admin_column'] = true;
	}

	return $args;
}, 10, 2);

Let’s go over it in more detail:

add_action('init', function()
{
	register_taxonomy_for_object_type('tree', 'fruit');
});

The WordPress core function `register_taxonomy_for_object_type` links a taxonomy to a post type. This means you can associate different post types and taxonomies without having to do it only during taxonomy registration.

The next code block enables the display of the “Tree” taxonomy column in the “Fruits” post type admin list:

add_filter('register_taxonomy_args', function($args, $taxonomy)
{
	if($taxonomy == 'tree')
	{
		$args['show_admin_column'] = true;
	}

	return $args;
}, 10, 2);

That’s all.

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 *