如何在文章编辑区向贡献者隐藏指定分类?Members插件代码自定义遇阻
Hide Specific Categories from Contributors in Post Edit/Add Screens (Members Plugin)
Hey there! Let's get this sorted—you want contributors to only see the "bloggers" category when they're creating or editing posts, while hiding "news", "blog", and "main". The Members plugin has the right hooks for this, but the generic code you found needs targeted tweaks to work properly. Here's a custom solution:
Step-by-Step Custom Code
Add this to your theme's functions.php file (or a custom functionality plugin for safer, theme-update-proof code):
add_filter( 'members_get_available_terms', 'restrict_contributor_categories', 10, 4 ); function restrict_contributor_categories( $terms, $taxonomy, $user_id, $args ) { // Only target the category taxonomy if ( 'category' !== $taxonomy ) { return $terms; } // Get the current logged-in user $current_user = wp_get_current_user(); // Exit if the user isn't a contributor if ( ! in_array( 'contributor', $current_user->roles ) ) { return $terms; } // Make sure we're only running this on post edit/add screens $current_screen = get_current_screen(); if ( ! $current_screen || ! in_array( $current_screen->id, array( 'post', 'edit-post' ) ) ) { return $terms; } // Define which categories to hide (use slugs here; swap with IDs if needed) $categories_to_hide = array( 'news', 'blog', 'main' ); // Filter out the hidden categories, keep everything else (including "bloggers") $filtered_terms = array_filter( $terms, function( $term ) use ( $categories_to_hide ) { return ! in_array( $term->slug, $categories_to_hide ); } ); return $filtered_terms; }
Key Details & Notes
- Members Plugin Requirement: This code relies on the
members_get_available_termshook from the Members plugin, so make sure the plugin is activated first—otherwise the code won't do anything. - Slug vs. ID: If you prefer to use category IDs instead of slugs (sometimes more reliable if slugs change), update
$categories_to_hideto something likearray( 5, 10, 15 )(replace with your actual category IDs). - Safety First: Adding code to
functions.phpcan break your site if there's a typo. Always back up your site first, or use a custom functionality plugin (create a simple plugin file with the code, upload to/wp-content/plugins/and activate it). - Testing: Log in with a contributor account, navigate to "Add New Post" or edit an existing post—you should only see the "bloggers" category in the categories metabox.
内容的提问来源于stack exchange,提问作者Merkucio
相关产品推荐
相关产品推荐

