php - 根据 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);
任何帮助高度赞赏。
解决方案
你的代码有一些错误
WC()->session->get( 'chosen_payment_method' );
在 foreach 循环外使用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' );
推荐阅读
- vba - 访问 Chr 函数返回不同的代码
- python - 如何在 JSON 中打印 dict 中的字符串列表
- r - 使用 SjPlot 绘制回归时更改交互项的标签
- mysql - MySQL子查询不返回相关结果
- python - 如何修改通过 df.loc[row] 定义的系列中的数据框元素?
- mongodb - Javers - 无法在文档中跟踪 mongo 更新
- python - 使用 Cloud Function 默认服务帐号访问 Gmail API
- java - Flink DataStream 如何将自定义的 POJO 合并到另一个 DataStream 中
- cuda - 这些方式是合并访问吗?
- javascript - 一种更快的编号方法