我想根据所选的支付网关为购物车商品价格添加百分比值。
我面临的问题是产品价格的变化没有根据产品价格进行更新。最初选择的价格一直在显示。
如何获得相应的更改价格?
到目前为止我的代码:
// 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' );