You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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., DE for Germany, DK for Denmark). You can add more codes to the $hidden_countries array as needed.
  • Wholesale Role: If your wholesale customer role has a different name (like wholesale instead of wholesale_customer), replace that string in the in_array check to match your actual role.
  • Safety First: Adding code to your main theme's functions.php can 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:32:28