我正在尝试根据自定义复选框是否被选中,为结账添加费用。我已经接近成功了,但是在获取POST值以确定是否应该应用费用时遇到了问题。
这是我自定义字段的代码:
add_action( 'woocommerce_after_checkout_billing_form', 'my_custom_fields' );
function my_custom_fields( $checkout ) {
echo '<div id="message_fields"><h3>' . __('Add a Message') . '</h3>';
woocommerce_form_field( 'add_gift_message', array(
'type' => 'checkbox',
'class' => array('gift_message form-row-wide'),
'label' => __('5x7 Enclosed Personal Message - $4'),
'placeholder' => __(''),
), $checkout->get_value( 'add_gift_message' ));
woocommerce_form_field( 'gift_message', array(
'type' => 'textarea',
'class' => array('gift_message_text form-row-wide'),
'label' => false,
'placeholder' => __('Your message'),
), $checkout->get_value( 'gift_message' ));
echo '</div>';
}
这个可以运行,字段显示很好。
在我的主题中的form-checkout.php底部,我添加了以下Javascript代码,当选中该字段时更新购物车总额:
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
$('#add_gift_message').click(function(){
if ( $(this).is(':checked') ) {
$('#gift_message_field').show();
var gift_message= true;
} else {
$('#gift_message_field').hide();
var gift_message = false;
}
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: $( 'form.checkout' ).serialize(),
success: function( response ) {
if ( response ) {
var order_output = $(response);
$( '#order_review' ).html( $.trim( order_output ) );
$('body').trigger('update_checkout');
}
},
error: function(code){
},
dataType: 'html'
});
});
});
</script>
这会更新订单总额并运行以下代码(这就是问题所在):
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $data ){
global $woocommerce;
if ( isset($_POST['add_gift_message']) )
$woocommerce->cart->add_fee( 'Personal Gift Message', '4.00', true, 'standard' );
}
我知道这一部分被称为,因为如果我删除if ( isset($_POST['add_gift_message']) ),它会添加费用。我遇到的问题是确定该字段是否已被选中 - 无论我做什么,我似乎都无法在woo_add_cart_fee内获取POST值。
有人知道如何让它正常工作吗?谢谢!!