You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在发布元框中按自定义用户角色控制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-approved are 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 the post_status column in your wp_posts database 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

  1. Log in to your WP admin with a user assigned to the cm role
  2. 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
  3. Repeat the process with an rm role user to confirm they see their three allowed statuses

内容的提问来源于stack exchange,提问作者Aaron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:08:45