WooCommerce 教程:隐藏非管理员的 WP-admin
我今天正在玩自己的结帐设计和 UX,而在测试时,我意识到新客户可以在购买后访问 WP 管理黑色条。所以 – 我说 – 容易的任务!
但是经过 20 分钟的现实(以为是需要 1 分钟),我终于找到了这个问题。和往常一样,这个博客自带的解决方案 – 随意使用这个修复在您自己的 WooSite
1. 隐藏 WP 管理员:理论
WordPress 为我们提供了一个名为 “ show_admin_bar ” 的过滤器。容易的愚蠢 – 将其设置为 false,管理员栏已经消失:
// Disable admin bar for non admins (this would work on a non-Woo site...)
function bbloomer_hide_admin_bar_if( $show ) {
if ( /* CONDITION */ ) $show = false;
return $show;
}
add_filter( 'show_admin_bar', 'bbloomer_hide_admin_bar_if' );
2. 隐藏 WP 管理员:Woo Reality
After the above snippet wouldn’t work on a Woo install, I did a lot of research. Tried other snippets but nothing. So, I said to myself… what if WooCommerce is ALREADY using that filter and I’m trying to edit the behavior of something that Woo is already modifying?
Well… here’s what I found in woocommerceincludeswc-user-functions.php:
/**
* Prevent any user who cannot 'edit_posts' (subscribers, customers etc) from seeing the admin bar.
*
*/
function wc_disable_admin_bar( $show_admin_bar ) {
if ( apply_filters( 'woocommerce_disable_admin_bar', get_option( 'woocommerce_lock_down_admin', 'yes' ) === 'yes' ) && ! ( current_user_can( 'edit_posts' ) || current_user_can( 'manage_woocommerce' ) ) ) {
$show_admin_bar = false;
}
return $show_admin_bar;
}
add_filter( 'show_admin_bar', 'wc_disable_admin_bar', 10, 1 );
See, something is already using the filter “show_admin_bar”, and what matters the most – the priority specified there is “10”.
Basically I was changing the behavior of the WP Admin Bar, but then WooCommerce was re-changing it after my call – in fact without specifying the priority, my filter got a default priority of “10”, too early to expect Woo NOT to re-change such functionality.
If this is not clear, and you’d rather get the fix – well, not to worry, here it is.
3. 隐藏非管理员的 WP 管理栏:WooCommerce PHP Snippet
/**
* @snippet WooCommerce Hide WP Admin Bar for non-Admins
* @sourcecode https://businessbloomer.com/?p=21213
* @author Rodolfo Melogli
* @testedwith WooCommerce 2.6.7
*/
function bbloomer_hide_admin_bar_if_non_admin( $show ) {
if ( ! current_user_can( 'administrator' ) ) $show = false;
return $show;
}
add_filter( 'show_admin_bar', 'bbloomer_hide_admin_bar_if_non_admin', 20, 1 );
// please note the priority = '20' to make sure we run the filter after Woo's one
如何添加此代码?
1 、您可以将 PHP 代码片段放置在主题或子主题的 functions.php 文件的底部(如果是 CSS 代码,请添加到子主题的 style.css 文件底部)修改之前建议先备份原始文件,若出现错误请先删除此代码。
2 、 WordPress 4.9 后改进了主题编辑器,对于 CSS 代码也可打开网站前台编辑器的【自定义】,复制代码添加到自定义 css 中。
此代码是否可用?
如需帮助或是您有更好的方案想分享?请到薇晓朵 WooCommerce 中文论坛留言告知,我们希望可以帮到更多国内的 WooCommerce 用户也希望您的参与。