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:
- 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).
- 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.
