在WooCommerce中根据支付方式提高购物车项目价格 [英] Increase cart item prices based on payment method in WooCommerce

查看:103
本文介绍了在WooCommerce中根据支付方式提高购物车项目价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要根据选定的支付网关向购物车项目价格添加百分比值。

我面临的问题是产品价格的变化没有随着产品价格的变化而更新。初始选择的价格始终显示。

我如何才能获得相应的更改价格?

我到目前为止的代码:

// Set custom cart item price
function add_custom_price( $cart ) {

    // This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example | optional)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        $chosen_payment_method = WC()->session->get('chosen_payment_method');

        if($chosen_payment_method == 'cod') {
            $increaseby =  3;
        } elseif($chosen_payment_method == 'paypal') {
            $increaseby =  8;
        } else {
            $increaseby =  10;
        }

        $price = get_post_meta($cart_item['product_id'] , '_price', true);
        $price = $price + (($price * $increaseby)/100);
        $cart_item['data']->set_price( $price );
    }
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);

我们非常感谢您的帮助。

推荐答案

您的代码中有一些错误

  • 在Foreach循环外部使用WC()->session->get( 'chosen_payment_method' );
  • get_post_meta()不需要获取价格,可以使用get_price()
  • 您还需要更改支付方式时触发的jQuery。

因此您得到:

function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Get payment method
    $chosen_payment_method = WC()->session->get( 'chosen_payment_method' );

    // Compare
    if ( $chosen_payment_method == 'cod' ) {
        $increaseby = 3;
    } elseif ( $chosen_payment_method == 'paypal' ) {
        $increaseby = 8;
    } else {
        $increaseby = 10;
    }

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {     
        // Get price
        $price = $cart_item['data']->get_price();

        // Set price
        $cart_item['data']->set_price( $price + ( $price * $increaseby ) / 100 );
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );    

function action_wp_footer() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
        jQuery(function($){
            $( 'form.checkout' ).on( 'change', 'input[name="payment_method"]', function() {
                $(document.body).trigger( 'update_checkout' );
            });
        });
    </script>
    <?php
    endif;
}
add_action( 'wp_footer', 'action_wp_footer' );

这篇关于在WooCommerce中根据支付方式提高购物车项目价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆