WooCommerce开发需求:添加PHP代码实现非批发客户结账页面隐藏指定国家
Hide Specific Countries on Checkout for Non-Wholesale Customers in WooCommerce
Hey there, here's a reliable way to hide countries like Germany (DE) and Denmark (DK) from the checkout page when the user isn't logged in as a wholesale customer. You'll add this PHP code to your theme's functions.php file (or better yet, a custom plugin to avoid losing changes when your theme updates):
/** * Hide specific countries on checkout for non-wholesale customers */ function wc_hide_countries_for_non_wholesale_customers( $countries ) { // Define the countries you want to hide (use ISO 3166-1 alpha-2 codes) $hidden_countries = array( 'DE', 'DK' ); // Get current user $current_user = wp_get_current_user(); // Check if user is NOT a wholesale customer (adjust the role name if yours is different) if ( ! in_array( 'wholesale_customer', $current_user->roles ) ) { // Remove the hidden countries from the available countries array foreach ( $hidden_countries as $country_code ) { if ( isset( $countries[ $country_code ] ) ) { unset( $countries[ $country_code ] ); } } } return $countries; } add_filter( 'woocommerce_countries', 'wc_hide_countries_for_non_wholesale_customers', 10, 1 );
Key Notes & Customizations:
- Country Codes: Make sure you're using the correct ISO 3166-1 alpha-2 codes for the countries you want to hide (e.g.,
DEfor Germany,DKfor Denmark). You can add more codes to the$hidden_countriesarray as needed. - Wholesale Role: If your wholesale customer role has a different name (like
wholesaleinstead ofwholesale_customer), replace that string in thein_arraycheck to match your actual role. - Safety First: Adding code to your main theme's
functions.phpcan be risky if the theme gets updated. I strongly recommend using a child theme or a custom plugin to keep this code intact long-term. - Testing: After adding the code, test both scenarios:
- Logged in as a wholesale customer: The hidden countries should appear in the checkout country dropdown.
- Logged out or logged in as a non-wholesale customer: Those countries should be hidden.
If you need to target only logged-out users plus non-wholesale logged-in users, this code already handles that—since logged-out users won't have the wholesale_customer role, the countries will be hidden for them too.
内容的提问来源于stack exchange,提问作者Martijn
相关产品推荐
相关产品推荐

