首页 > 解决方案 > 在 Woocommerce 中禁用特定付款方式的送货方式

问题描述

在 Woocommerce 上,我启用了 2 种送货方式:免费送货或统一费率。我启用了 2 种付款方式:银行转账(bacs)和 PayPal (paypal)

我想要实现的目标:如果客户选择 PayPal 作为支付类型,他应该被迫选择“统一费率”作为运输方式。“免费送货”应该隐藏或显示为灰色或类似的东西。

如果选择银行转帐,那么两种运输方式都应该可用。

任何帮助表示赞赏。

标签: phpwordpresswoocommercepayment-gatewayshipping-method

解决方案


更新 2:当“paypal”是选择的付款方式时,以下代码将禁用“ free_shipping”运输方式(方法 ID) :

add_filter( 'woocommerce_package_rates', 'shipping_methods_based_on_chosen_payment', 100, 2 );
function shipping_methods_based_on_chosen_payment( $rates, $package ) {
    // Checking if "paypal" is the chosen payment method
    if ( WC()->session->get( 'chosen_payment_method' ) === 'paypal' ) {
        // Loop through shipping methods rates
        foreach( $rates as $rate_key => $rate ){
            if ( 'free_shipping' === $rate->method_id ) {
                unset($rates[$rate_key]); // Remove 'Free shipping'shipping method
            }
        }
    }
    return $rates;
}

// Enabling, disabling and refreshing session shipping methods data
add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
    $bool = true;
    if ( WC()->session->get('chosen_payment_method' ) ) $bool = false;

    // Mandatory to make it work with shipping methods
    foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){
        WC()->session->set( 'shipping_for_package_' . $package_key, $bool );
    }
    WC()->cart->calculate_shipping();
}

// Jquery script for checkout page
add_action('wp_footer', 'refresh_checkout_on_payment_method_change' );
function refresh_checkout_on_payment_method_change() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):
    ?>
    <script type="text/javascript">
    jQuery(function($){
        // On shipping method change
        $('form.checkout').on( 'change', 'input[name^="payment_method"]', function(){
            $('body').trigger('update_checkout'); // Trigger Ajax checkout refresh
        });
    })
    </script>
    <?php
    endif;
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

要获取相关的运输方式费率 ID,例如flat_rate:12,请使用浏览器代码检查器检查每个相关的单选按钮属性name,例如:

在此处输入图像描述


注意:由于 WooCommerce 新版本发生变化,抱歉,代码不再工作


推荐阅读