我今天正在玩自己的結帳設計和 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 使用者也希望您的參與。