I’ve created some custom taxonomies using register_taxonomy, but I want to prevent new terms from being added. I noticed that there is a ‘capabilities’ argument available in register_taxonomy, is that what I should be using and if so, how would I use it?
Here’s some of my code, I’m using a plugin I created to add the taxonomies (hence the public static function part). Is there an easy way to prevent new terms being created for my taxonomy?
Thanks
Osu
public static function register_directory_styles_taxonomy()
{
$labels = array(
'name' => 'Music styles',
'singular_name' => 'Music style',
'search_items' => 'Search music styles',
'all_items' => 'All music styles',
'parent_item' => 'Parent music style',
'edit_item' => 'Edit music style',
'update_item' => 'Update music style',
'add_new_item' => 'Add new music style',
'new_item_name' => 'New music style',
'choose_from_most_used' => 'Choose from most used music styles'
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'rewrite' => false
// 'show_ui' => false
);
register_taxonomy( 'ibmstyles', 'ibmdirectory', $args );
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can block addition of new terms with a filter on pre_insert_term. The source is helpful in working out what you can do.
add_action( 'pre_insert_term', function ( $term, $taxonomy )
{
return ( 'yourtax' === $taxonomy )
? new WP_Error( 'term_addition_blocked', __( 'You cannot add terms to this taxonomy' ) )
: $term;
}, 0, 2 );
Method 2
It would seem the easiest way to do this has been answered here.
The solution was modifying the taxonomy’s capabilities array:
'capabilities' => array(
'manage_terms' => '',
'edit_terms' => '',
'delete_terms' => '',
'assign_terms' => 'edit_posts'
),
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0