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

WooCommerce限制店铺经理仅可查看编辑wc-processing状态订单代码片段

WooCommerce 店铺经理订单权限管控实现代码

以下代码可直接实现店铺经理仅可查看、编辑wc-processing(处理中)状态订单的需求,无需安装第三方权限插件,覆盖列表展示、直连拦截、编辑权限全场景校验,不会出现权限绕过。

// 过滤后台订单列表,店铺经理仅显示处理中状态订单
add_action('pre_get_posts', function($query) {
    global $pagenow, $post_type;
    // 跳过非后台、非订单列表页、非店铺经理角色的请求
    if (!is_admin() || $pagenow !== 'edit.php' || $post_type !== 'shop_order' || !current_user_can('shop_manager')) {
        return;
    }
    // 强制查询条件限定为处理中状态
    $query->set('post_status', 'wc-processing');
});

// 拦截店铺经理通过URL直接访问非处理中状态订单的请求
add_action('load-post.php', function() {
    if (!is_admin() || !current_user_can('shop_manager') || !isset($_GET['post']) || get_post_type($_GET['post']) !== 'shop_order') {
        return;
    }
    $order_status = get_post_status($_GET['post']);
    if ($order_status !== 'wc-processing') {
        wp_die('*权限不足:您仅可查看、编辑处理中状态的订单*');
    }
});

// 权限映射层校验,彻底移除店铺经理对非处理中订单的编辑权限
add_filter('map_meta_cap', function($caps, $cap, $user_id, $args) {
    // 仅处理订单相关编辑权限校验
    if (!in_array($cap, ['edit_post', 'edit_shop_order', 'edit_shop_orders'])) {
        return $caps;
    }
    $user = get_userdata($user_id);
    if (!$user || !in_array('shop_manager', $user->roles)) {
        return $caps;
    }
    // 无具体订单ID时放行列表查询逻辑
    if (empty($args[0])) {
        return $caps;
    }
    $order_id = $args[0];
    if (get_post_type($order_id) !== 'shop_order') {
        return $caps;
    }
    // 非处理中状态订单直接禁止编辑
    if (get_post_status($order_id) !== 'wc-processing') {
        $caps[] = 'do_not_allow';
    }
    return $caps;
}, 10, 4);

使用注意事项

  • 代码可直接粘贴到当前启用主题/子主题的functions.php文件末尾,也可通过自定义代码片段插件插入,保存后立即生效
  • 所有校验逻辑仅对shop manager(店铺经理)角色生效,不会影响管理员、店主等其他角色的正常订单操作
  • 代码兼容WooCommerce默认post类型存储模式与HPOS高性能订单存储模式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:24:25