I have a custom post type which comes with a category taxonomy. This taxonomy shows as a meta box at the side. Pretty basic so far.
Now I want to add additional meta boxes below the content on the "normal" location. I want to display one meta box for each public taxonomy in the system. So far I use this code to add the boxes:
public function add_meta_boxes_rfe_taxonomy_related__premium_only($post)
{
$taxonomies = get_taxonomies(['public' => true], 'objects');
foreach ($taxonomies as $taxonomy) {
if ('rfe_taxonomy_related_category' === $taxonomy->name) {
continue;
}
$taxonomy_name = $taxonomy->labels->name;
$taxonomy_slug = $taxonomy->name;
$taxonomy_is_hierarchical = $taxonomy->hierarchical;
$object_type = $taxonomy->object_type;
$post_type_names = [];
foreach ($object_type as $post_type) {
$post_type_name = isset($post_type_names[$post_type]) ? $post_type_names[$post_type] : false;
if (!$post_type_name) {
$post_type_name = get_post_type_object($post_type)->label;
$post_type_names[$post_type] = $post_type_name;
}
if ($taxonomy_is_hierarchical) {
add_meta_box(
'rfe_taxonomy_related_meta_box_' . $taxonomy_slug, //ID
$taxonomy_name . ' (' . $post_type_name . ')', //Title
[$this, 'build_hierarchical_taxonomy_meta_box__premium_only'], //Callback
'rfe_taxonomy_related', //Post type to add to
'normal',
'low'
);
} else {
add_meta_box(
'rfe_taxonomy_related_meta_box_' . $taxonomy_slug, //ID
$taxonomy_name . ' (' . $post_type_name . ')', //Title
[$this, 'build_flat_taxonomy_meta_box__premium_only'], //Callback
'rfe_taxonomy_related', //Post type to add to
'normal',
'low'
);
}
}
}
}
public function build_hierarchical_taxonomy_meta_box__premium_only($post, $metabox)
{
$taxonomy_slug = substr($metabox['id'], strlen('rfe_taxonomy_related_meta_box_'));
$box['args']['taxonomy'] = $taxonomy_slug;
post_categories_meta_box($post, $box);
}
public function build_flat_taxonomy_meta_box__premium_only($post, $metabox)
{
$taxonomy_slug = substr($metabox['id'], strlen('rfe_taxonomy_related_meta_box_'));
$box['args']['taxonomy'] = $taxonomy_slug;
post_tags_meta_box($post, $box);
}
This already gives me the meta boxes but the meta boxes for the flat taxonomies do not seem to work. I cannot add new tags or select from the most popular ones.
The second issue is that when I save the post, all changes are lost. I wonder what I am missing or what I am doing wrong.
register_taxonomy_for_object_type()
function, to add already registered taxonomy to your custom post type. Maybe take a look here: https://pippinsplugins.com/add-already-registered-taxonomy/ or the Codex linkregister_taxonomy_for_object_type
first but it adds the meta boxes to the side and it can get confusing if you have two taxonomies called "Categories" but on different post types.register_taxonomy_for_object_type
, after thatremove_meta_box
and thanadd_meta_box
again with a custom context/position. But seems like an overhead.