Php 在Woocommerce中根据装运方式和付款方式添加费用

Php 在Woocommerce中根据装运方式和付款方式添加费用,php,jquery,wordpress,woocommerce,checkout,Php,Jquery,Wordpress,Woocommerce,Checkout,我需要申请一个额外的费用时,客户可以下订单,免费送货,但想选择COD付款。 所以,免费送货+货到付款=>费用 我尝试了以下代码,但没有成功。我错在哪里 add_action( 'woocommerce_cart_calculate_fees','cod_fee' ); function cod_fee() { global $woocommerce; if ( is_admin() && ! defined( 'DOING_AJAX' ) ) r

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

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

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, '' );
    }
}

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

// 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文件。测试和工作。

LoicTheAztec,因为我尝试了此代码,它工作得很好,但一旦订单付款失败,用户再次尝试从订单历史付款,则不会收到任何cod费用added@ParthShah是的,这是正常的,因为这段代码不处理这种情况,因为这里在checkout页面中只在Cart对象上使用钩子。如果订单失败,为了支付订单,购物车对象将不再存在。因此,在这种情况下,商店经理需要编辑订单并添加费用。因此,我如何添加费用?您能帮我吗。。有任何挂钩或条件吗?但是发送给用户的带有最终付款的邮件,因此我们无法从后端更改金额没有挂钩可用??我不知道…我的答案只是现有非工作代码的工作更改版本。因此,这个答案只是修补现有的代码,使其工作。您所要求的是完全不同的东西,没有提供任何代码。