Recently I faced a scenario where I had to prevent certain users from adding new terms to some custom taxonomies that I created. After some research I found that there isn’t a straight forward way to do this using user capabilities or roles.
The only way is to use the pre_insert_term
hook and black-list taxonomies based on user capabilities. I am sharing the code here so that it would be useful for people who want to something similar.
In the above code change the taxonomy name and capability to suit your usecase.
I think that if you are not returning an error then the function has to return the term name, i.e.:
return $term
…otherwise you receive an error that the term name has to be populated
Oops, I completely missed it.
Just updated the gist (It will get updated in the post once the cache is cleared). Thanks for letting me know about it.
Exactly what I needed. Thanks!
Glad to know that it was useful to you.
Thanks for this, it gave me a good start on what I was trying to do! In my case, I want to block any users from adding or deleting any terms within a multisite, as I want all terms to be sync’ed from a central plugin ala Network Terminator. I used your code to block adding new terms for all but super administrators:
if ( !current_user_can( ‘manage_network’ ) )
Having trouble posting my full comment, so will try breaking it into two parts…
I’m having more difficulty blocking deletion of terms, I think because pre_delete_term uses do_action rather than apply_filters, so does not incorporate a return’ed value to check for errors.
The following code works to block deletion, but with the error “An unidentified error has occurred.” So it works, but isn’t informative and may break in the future. Maybe this will help others, and maybe others will know a better way to do it:
add_action( ‘pre_delete_term’, ‘prevent_terms_delete’, 1, 2 );
function prevent_terms_delete ( $term, $taxonomy ) {
if ( !current_user_can( ‘manage_network’ ) ) {
echo ( ‘You cannot delete terms (categories, tags, etc)’ );
}
}
Hello Norris,
Thanks for sharing the code snippet.
Thanks for this. Exactly what I needed, but the error message doesn’t come up for me. Do you have any idea why?