隐藏woocommerce设置选项卡
我想按用户角色隐藏特定woocommerce设置选项卡。不是整个子菜单,而只是一个标签(检查具体)。 我希望店铺经理能够访问大部分设置,但无法影响结帐设置。隐藏woocommerce设置选项卡
我该如何做到这一点?
如果你想删除的标签,而不是使用CSS隐藏它们,那么你可以添加以下到你的主题的functions.php:
add_filter('woocommerce_settings_tabs_array', 'remove_woocommerce_setting_tabs', 200, 1);
function remove_woocommerce_setting_tabs($tabs) {
// Declare the tabs we want to hide
$tabs_to_hide = array(
'Tax',
'Checkout',
'Emails',
'API',
'Accounts',
);
// Get the current user
$user = wp_get_current_user();
// Check if user is a shop-manager
if (isset($user->roles[0]) && $user->roles[0] == 'shop_manager') {
// Remove the tabs we want to hide
$tabs = array_diff($tabs, $tabs_to_hide);
}
return $tabs;
}
这使用WooCommerce的'woocommerce_settings_tabs_array'过滤器。有关所有WooCommerce过滤器和挂钩的更多信息,请看这里:https://docs.woocommerce.com/wc-apidocs/hook-docs.html
这样做的好处是它不再处于HTML中,因此如果有人查看源代码,他们将无法找到元素。
您仍然可以访问这些网址。这只是删除标签而不是隐藏它们的一种方式。
编辑: 我已经想出了如何停止访问URL。复制以下内容:
add_filter('woocommerce_settings_tabs_array', 'remove_woocommerce_setting_tabs', 200, 1);
function remove_woocommerce_setting_tabs($array) {
// Declare the tabs we want to hide
$tabs_to_hide = array(
'tax' => 'Tax',
'checkout' => 'Checkout',
'email' => 'Emails',
'api' => 'API',
'account' => 'Accounts',
);
// Get the current user
$user = wp_get_current_user();
// Check if user is a shop_manager
if (isset($user->roles[0]) && $user->roles[0] == 'shop_manager') {
// Remove the tabs we want to hide from the array
$array = array_diff_key($array, $tabs_to_hide);
// Loop through the tabs we want to remove and hook into their settings action
foreach($tabs_to_hide as $tabs => $tab_title) {
add_action('woocommerce_settings_' . $tabs , 'redirect_from_tab_page');
}
}
return $array;
}
function redirect_from_tab_page() {
// Get the Admin URL and then redirect to it
$admin_url = get_admin_url();
wp_redirect($admin_url);
exit;
}
这与第一位代码几乎相同,除了数组的结构不同,我添加了一个foreach。该foreach遍历我们想要阻止的选项卡列表,并挂接到用于显示设置页面的'woocommerce_settings _ {$ tab}'操作。
然后我创建了一个redirect_from_tab_page函数来将用户重定向到默认的管理员URL。这会停止直接访问不同的设置选项卡。
将这个代码在你的主题/子主题的functions.php或别的地方:
if (!function_exists('hide_setting_checkout_for_shop_manager')){
function hide_setting_checkout_for_shop_manager() {
$user = wp_get_current_user();
//check if user is shop_manager
if (isset($user->roles[0]) && $user->roles[0] == 'shop_manager') {
echo '<style> .woocommerce_page_wc-settings form .woo-nav-tab-wrapper a[href="'.admin_url('admin.php?page=wc-settings&tab=checkout').'"]{ display: none; } </style>';
}
}
}
add_action('admin_head', 'hide_setting_checkout_for_shop_manager');
风格将输出到HTML头只在WP-admin和登录用户的角色是shop_manager。
更多关于admin_head钩,请https://codex.wordpress.org/Plugin_API/Action_Reference/admin_head
是的,这是正确的。好的回答 – LoicTheAztec
非常感谢。这工作完美。 但是,如果他们谦虚地键入网址,他们可以访问该页面。 我实际上希望能够阻止他们访问该页面。我想你回答了这个问题,虽然 –
感谢你。 我最终使用重定向规则来阻止访问url本身。 –
看到我更新的答案,我得到了这个使用动作钩子的工作。在WordPress中使用重定向规则可能会更容易。我想这样做,因为我的WordPress是多站点安装。 –
太好了。我也想用它来进行多站点安装。 我应该将此答案标记为已接受 –