如何让WooCommerce自定义角色Marron仅查看自身后台订单?
解决方案
1. 确认Marron角色的基础权限
先保证Marron角色只拥有以下权限,不要给任何编辑/修改订单的权限:
read:允许访问WordPress后台view_woocommerce_orders:允许查看WooCommerce订单列表(如果角色没有这个权限,用用户角色编辑器插件手动添加即可)
2. 添加自定义代码实现权限限制
把下面的代码添加到你的主题functions.php文件,或者创建一个简单的自定义插件来存放这段代码:
// 过滤后台订单列表,仅显示当前用户的订单 add_action('pre_get_posts', 'restrict_marron_to_own_orders'); function restrict_marron_to_own_orders($query) { global $pagenow; $current_user = wp_get_current_user(); // 仅在后台订单列表页面生效,且当前用户是Marron角色 if (is_admin() && $pagenow === 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'shop_order' && in_array('marron', $current_user->roles)) { // 只查询当前用户作为客户的订单 $query->set('meta_key', '_customer_user'); $query->set('meta_value', $current_user->ID); $query->set('meta_compare', '='); } } // 限制订单详情页访问,禁止查看他人订单 add_action('load-post.php', 'block_marron_access_to_other_orders'); add_action('load-post-new.php', 'block_marron_access_to_other_orders'); function block_marron_access_to_other_orders() { $post_id = isset($_GET['post']) ? intval($_GET['post']) : 0; $current_user = wp_get_current_user(); if ($post_id && in_array('marron', $current_user->roles)) { $order = wc_get_order($post_id); if ($order && $order->get_customer_id() !== $current_user->ID) { // 跳回订单列表页 wp_safe_redirect(admin_url('edit.php?post_type=shop_order')); exit; } } } // 移除订单列表中的编辑操作入口 add_filter('post_row_actions', 'remove_edit_actions_for_marron', 10, 2); function remove_edit_actions_for_marron($actions, $post) { $current_user = wp_get_current_user(); if ($post->post_type === 'shop_order' && in_array('marron', $current_user->roles)) { unset($actions['edit']); unset($actions['inline hide-if-no-js']); // 移除快速编辑 } return $actions; }
3. 代码作用说明
pre_get_posts:修改后台订单列表的查询逻辑,只加载当前用户作为下单客户的订单。load-post.php/load-post-new.php:防止用户直接通过URL访问不属于自己的订单详情页,一旦检测到就跳回订单列表。post_row_actions:移除订单列表里的编辑、快速编辑按钮,彻底切断编辑入口。
4. 验证效果
用Marron角色的账号登录后台,进入订单列表:
- 只能看到自己的订单
- 订单列表中没有编辑选项
- 尝试手动输入他人订单的详情页URL,会自动跳回订单列表
内容的提问来源于stack exchange,提问作者Gelebrin7
相关产品推荐
相关产品推荐

