我想根据结帐页面上的自定义字段值更改购物车总价。使用jQuery,我会触发“ update_checkout ”,并在子主题的 functions.php 文件中具有“ woocommerce_before_calculate_totals ”钩子。在此处获取自定义结帐字段值,并在挂钩中更新购物车项目价格。一切正常在这里工作,并且结帐页面已使用新的总计更新。我下订单时,订单价格中有商品的原始价格。 我希望订单具有修改/更新的价格。 这是我的代码
JavaScript
jQuery(document).ready(function($) {
$( document.body ).on( 'updated_checkout',function(){
$('#number_of_kids').on('change',function(){
$( document.body ).trigger( 'update_checkout');
});
});
});
PHP Woocommerce钩子
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1, 20);
function add_custom_price( $cart_obj ) {
if( isset($_POST['post_data']) ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
parse_str($_POST['post_data'], $post_data);
foreach ( $cart_obj->get_cart() as $cart_item ) {
$newAmount = 0;
if(isset($post_data['number_of_kids']) && 10 < $post_data['number_of_kids']){
$newAmount = 100;
}
$cart_item['data']->set_price( $cart_item['data']->get_price() + $newAmount );
}
}
}
``