【发布时间】:2016-08-15 05:27:54
【问题描述】:
我想按用户角色隐藏特定的 woocommerce 设置选项卡。不是整个子菜单,而只是一个选项卡(具体结帐)。 我希望商店经理能够访问大部分设置,但不能影响结帐设置。
我怎样才能做到这一点?
【问题讨论】:
标签: wordpress woocommerce
我想按用户角色隐藏特定的 woocommerce 设置选项卡。不是整个子菜单,而只是一个选项卡(具体结帐)。 我希望商店经理能够访问大部分设置,但不能影响结帐设置。
我怎样才能做到这一点?
【问题讨论】:
标签: wordpress 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。这只是一种删除选项卡而不是隐藏它们的方法。
编辑: 我已经弄清楚如何停止对 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');
样式只会在wp-admin输出到html head,登录用户角色为shop_manager。
更多关于admin_head hook,请查看https://codex.wordpress.org/Plugin_API/Action_Reference/admin_head
【讨论】: