且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Woocommerce中添加基于运输方式和付款方式的费用

更新时间:2023-11-30 13:29:16

您的代码有误,需要一些其他代码.尝试下面的代码选择的支付方法时,将添加一个特定的费用是货到付款(COD)和选择的运输方式时是免费送货":

There is a mistake in your code and some additional code is needed. Try the following code that will add a specific fee when chosen payment method is Cash on delivery (cod) and when chosen shipping methods is "Free shipping":

// Add a conditional fee
add_action( 'woocommerce_cart_calculate_fees', 'add_cod_fee', 20, 1 );
function add_cod_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    ## ------ Your Settings (below) ------ ##
    $your_payment_id      = 'cod'; // The payment method
    $your_shipping_method = 'free_shipping'; // The shipping method
    $fee_amount           = 19; // The fee amount
    ## ----------------------------------- ##

    $chosen_payment_method_id  = WC()->session->get( 'chosen_payment_method' );
    $chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
    $chosen_shipping_method    = explode( ':', $chosen_shipping_method_id )[0];

    if ( $chosen_shipping_method == $your_shipping_method 
    && $chosen_payment_method_id == $your_payment_id ) {
        $fee_text = __( "Spese per pagamento alla consegna", "woocommerce" );
        $cart->add_fee( $fee_text, $fee_amount, false );
    }
}

// Refresh checkout on payment method change
add_action( 'wp_footer', 'refresh_checkout_script' );
function refresh_checkout_script() {
    // Only on checkout page
    if( is_checkout() && ! is_wc_endpoint_url('order-received') ) :
    ?>
    <script type="text/javascript">
    jQuery(function($){
        // On payment method change
        $('form.woocommerce-checkout').on( 'change', 'input[name="payment_method"]', function(){
            // Refresh checkout
            $('body').trigger('update_checkout');
        });
    })
    </script>
    <?php
    endif;
}

代码进入您的活动子主题(或活动主题)的functions.php文件中.经过测试并可以工作.

Code goes in functions.php file of your active child theme (or active theme). tested and works.