根据 WooCommerce 中的付款方式增加购物车商品价格

Increase cart item prices based on payment method in 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' );