基于Woocommerce 结帐分析代码中的单选按钮动态更新费用。我正在尝试使其与 WooCommerce 结帐时的不同包装选项一起使用。
这个想法是能够提供礼品包装、袋装等选项。
问题是,它为我提供了可选择的选项,但是因为它正在打印标签的 HTML 而不是什么,所以一切都搞砸了。
这是我正在使用的代码:
add_action( 'woocommerce_form_field_radio', 'gift_bag_none', 20, 4 );
function gift_bag_none( $field, $key, $args, $value ) {
if ( ! empty( $args['options'] ) && is_checkout() ) {
$field = str_replace( '</label><input ', '</label><br><input ', $field );
$field = str_replace( '<label ', '<label style="display:inline;margin-left:8px;" ', $field );
}
return $field;
}
add_action( 'woocommerce_cart_calculate_fees', 'gift_bag_none_fee', 20, 1 );
function gift_bag_none_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$packing_fee = WC()->session->get( 'chosen_packing' );
if( $packing_fee === 'box' )
$fee = 29.00;
else if( $packing_fee === 'none' )
$fee = 0.00;
else if( $packing_fee === 'both' )
$fee = 25.00;
else
$fee = 5.00;
$cart->add_fee( __( 'Packaging Cost', 'woocommerce' ), $fee );
}
add_action( 'woocommerce_review_order_after_shipping', 'checkout_packing_addition', 20 );
function checkout_packing_addition() {
$domain = 'woocommerce';
echo '<tr><th>' . __('Packaging Options', $domain) . '</th><td>';
echo '<tr class="packing-select"><th>' . __('In a bag?<br>Boxed and wrapped as gift?<br><span style="color:red;">Boxed, wrapped and in a bag?</span><br>Or just the product?', $domain) . '</th><td>';
$chosen = WC()->session->get('chosen_packing');
$chosen = empty($chosen) ? WC()->checkout->get_value('radio_packing') : $chosen;
$chosen = empty($chosen) ? 'none' : $chosen;
woocommerce_form_field( 'radio_packing', array(
'type' => 'radio',
'class' => array( 'form-row-wide packing' ),
'options' => array(
'bag' => __('Yes, give it to me in a bag for '.wc_price(5.00), $domain),
'box' => __('Giftbox + Wrapping for '.wc_price(29.00), $domain),
'both' => __('Wrapped Giftbox in a Bag for '.wc_price(25.00), $domain),
'none' => __('Just the product at no extra cost '.wc_price(0.00), $domain)
),
'default' => $chosen,
), $chosen );
echo '</td></tr>';
}
add_action( 'wp_footer', 'checkout_packing_script' );
function checkout_packing_script(){ ?>
<script type="text/javascript">
jQuery( function($) {
$('form.checkout').on('change', 'input[name=radio_packing]', function(e){
e.preventDefault();
var p = $(this).val();
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'woo_get_ajax_data',
'packing': p,
},
success: function (result) {
$('body').trigger('update_checkout');
},
error: function(error){
}
});
});
});
</script>
<?php
}
add_action('wp_ajax_woo_get_ajax_data', 'packing_ajax_data');
add_action('wp_ajax_nopriv_woo_get_ajax_data', 'packing_ajax_data');
function packing_ajax_data() {
if ( isset($_POST['packing']) ){
$packing = sanitize_key( $_POST['packing'] );
WC()->session->set('chosen_packing', $packing );
echo json_encode( $packing );
}
die();
}