最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to conditionally hide payment method based on shipping country in WooCommerce block-based checkout? - Stack Overflow

programmeradmin4浏览0评论

I’m using the latest version of WooCommerce with the block-based checkout (i.e., WooCommerce Blocks), and I need to hide the default “Cash on Delivery” (COD) payment method unless the shipping country is German (DE).

In the classic checkout flow, this could easily be achieved using the woocommerce_available_payment_gateways filter:

add_filter('woocommerce_available_payment_gateways', 'custom_restrict_cod_for_slovenia');
function custom_restrict_cod_for_slovenia($gateways) {
    if (is_admin()) return $gateways;

    if (isset($gateways['cod'])) {
        $shipping_country = WC()->customer->get_shipping_country();
        if ($shipping_country !== 'DE') {
            unset($gateways['cod']);
        }
    }
    return $gateways;
}

This works perfectly in the classic checkout, but it does NOT work in the block-based checkout – the COD method still appears even if the shipping country is not Slovenia, and it doesn’t update dynamically when the user changes the country.

I’ve also tried hooking into woocommerce_store_api_payment_methods like this:

add_filter('woocommerce_store_api_payment_methods', 'custom_cod_for_si_only', 10, 2);
function custom_cod_for_si_only($gateways, $request) {
    if (isset($gateways['cod'])) {
        if (
            isset($request['shipping_address']['country']) &&
            $request['shipping_address']['country'] !== 'DE'
        ) {
            unset($gateways['cod']);
        }
    }
    return $gateways;
}

But even this doesn’t work as expected. The COD payment method still shows up regardless of the selected country, and doesn’t hide dynamically when switching the country at checkout.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论