Hello, How can I restrict the addition of new tags for users who are not administrators in Posts -> Tags?
1 Answer
To restrict non-administrators from adding new tags in the WordPress admin area, you can use a combination of WordPress hooks and capabilities checks. The idea is to disable the ability for users who are not administrators to create new tags while still allowing them to select from existing tags when editing posts.
Here's a custom function that you can add to your theme's functions.php
file or a custom plugin:
function wpb_restrict_tags_for_non_admins() {
if (!current_user_can('administrator')) {
// Remove the ability to add new tags
global $wp_taxonomies;
if (isset($wp_taxonomies['post_tag'])) {
$wp_taxonomies['post_tag']->cap->assign_terms = 'do_not_allow';
}
}
}
add_action('admin_init', 'wpb_restrict_tags_for_non_admins');
Explanation:
Check User Capability: current_user_can('administrator')
checks if the current user is an administrator. If not, the function proceeds to restrict the capability.
Modify Taxonomy Capabilities: The $wp_taxonomies
global variable holds information about all registered taxonomies, including tags (post_tag
). By changing the assign_terms
capability to an invalid capability (like 'do_not_allow
'), non-administrative users are prevented from adding new tags.
Hook into Admin Initialization: admin_init
is a hook that runs when the WordPress admin area initializes, making it a suitable place to put our capability check.
After adding this code to your WordPress site, only administrators will be able to add new tags, while other users can still choose from existing tags. This code snippet is specific to post tags (post_tag
taxonomy), so if you have custom taxonomies, you'll need to adjust the taxonomy name accordingly.
Please test this change in a staging environment before applying it to a live site, as changes in capabilities can have wide-reaching effects.