如何在发布元框中按自定义用户角色控制post_status可见性
Restrict Publish Meta Box Statuses by Custom User Roles
Hey there! I've got you covered on limiting which post statuses your cm and rm custom roles can see in the publish meta box. We'll use a WordPress filter hook to target each role and filter the available statuses specifically for them.
Step 1: Add the Filter Function
Drop this code into your theme's functions.php file or a custom functionality plugin (plugins are always safer for custom code, in case you switch themes later):
add_filter('get_available_post_statuses', 'filter_post_statuses_for_custom_roles', 10, 2); function filter_post_statuses_for_custom_roles($available_statuses, $post) { // Grab the current logged-in user $current_user = wp_get_current_user(); // Handle 'cm' role: only show 'cm approved' and 'cm rejected' if (in_array('cm', $current_user->roles)) { // Replace these slugs with your actual post status slugs! $allowed_statuses = ['cm-approved', 'cm-rejected']; foreach ($available_statuses as $slug => $label) { if (!in_array($slug, $allowed_statuses)) { unset($available_statuses[$slug]); } } } // Handle 'rm' role: show 'cm approved', 'rm approved', 'rm rejected' elseif (in_array('rm', $current_user->roles)) { // Again, replace slugs with your real ones $allowed_statuses = ['cm-approved', 'rm-approved', 'rm-rejected']; foreach ($available_statuses as $slug => $label) { if (!in_array($slug, $allowed_statuses)) { unset($available_statuses[$slug]); } } } return $available_statuses; }
Important Notes to Make This Work
- Replace Status Slugs: The slugs like
cm-approvedare placeholders. You need to swap these with the actual slugs you used when registering your custom post statuses. If you're not sure what they are, check your custom status registration code or look at thepost_statuscolumn in yourwp_postsdatabase table. - No Extra Permissions Needed: This function automatically checks the user's role and adjusts the statuses accordingly—no need to mess with additional capability settings.
- Compatibility: This works with WordPress 4.4 and newer, which covers almost all active sites these days.
How to Test It
- Log in to your WP admin with a user assigned to the
cmrole - Open any post edit screen and check the publish meta box's status dropdown—you should only see the two approved/rejected statuses for cm
- Repeat the process with an
rmrole user to confirm they see their three allowed statuses
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

