php - 根据 Woocommerce 中的运输方式和付款方式添加费用

标签 php jquery wordpress woocommerce checkout

当客户可以免运费下订单,但想要选择货到付款时,我需要申请额外费用。 所以,免费送货 + 货到付款 => 费用。

我尝试了以下代码,但没有成功。我哪里错了?

add_action( 'woocommerce_cart_calculate_fees','cod_fee' );
function cod_fee() {
    global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

        $chosen_gateway = WC()->session->chosen_payment_method;
        $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
        $chosen_shipping = $chosen_methods[0]; 
        $fee = 19;
        if ( $chosen_shipping == 'free_shipping' && $chosen_gateway == 'cod' ) { 
        WC()->cart->add_fee( 'Spese per pagamento alla consegna', $fee, false, '' );
    }
}

最佳答案

您的代码中有错误,需要一些额外的代码。尝试使用以下代码,当选择的付款方式为货到付款 (cod) 且选择的送货方式为“免运费”时,该代码将添加特定费用:

// 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 文件中。经过测试并有效。

关于php - 根据 Woocommerce 中的运输方式和付款方式添加费用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52138784/

相关文章:

php - mysql分页结果

javascript : focusOffset with html tags

javascript - 系统地更新 IMG 的 src。内存泄漏

javascript - 在wordpress中禁用移动 View 的js

javascript - 如何使用 JavaScript 将 id 设置为 session 值

php - 如何在向浏览器提供页面之前导出 cytoscape 网络图

jQuery + Css - 动态添加 css 到列表项

php - 如何在wordpress中更改像seo友好的url

wordpress - Polylang 字符串翻译中只有一种语言

php - PHP 中的 UTF-8 编码 xml