通过启用基于单选按钮选择的动态费用更新来增强您的 WooCommerce 结账体验。这使您可以提供不同的包装选项和费用,以满足客户的喜好。
在您的functions.php文件中实现以下代码以实现所需的功能:
<code class="php">// Add a custom dynamic packaging fee add_action( 'woocommerce_cart_calculate_fees', 'add_packaging_fee', 20, 1 ); function add_packaging_fee( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee $fee = $packing_fee === 'box' ? 9.00 : 3.00; $cart->add_fee( __( 'Packaging fee', 'woocommerce' ), $fee ); } // Add a custom radio fields for packaging selection add_action( 'woocommerce_review_order_after_shipping', 'checkout_shipping_form_packing_addition', 20 ); function checkout_shipping_form_packing_addition() { $domain = 'woocommerce'; echo '<tr class="packing-select"><th>' . __('Packing options', $domain) . '</th><td>'; $chosen = WC()->session->get('chosen_packing'); $chosen = empty($chosen) ? WC()->checkout->get_value('radio_packing') : $chosen; $chosen = empty($chosen) ? 'bag' : $chosen; // Add a custom checkbox field woocommerce_form_field( 'radio_packing', array( 'type' => 'radio', 'class' => array( 'form-row-wide packing' ), 'options' => array( 'bag' => __('In a bag '.wc_price(3.00), $domain), 'box' => __('In a gift box '.wc_price(9.00), $domain), ), 'default' => $chosen, ), $chosen ); echo '</td></tr>'; }</code>
为了确保单选按钮选择时的无缝更新,请实现此 JavaScript 和 AJAX 脚本:
<code class="javascript">// jQuery - Ajax script add_action( 'wp_footer', 'checkout_shipping_packing_script' ); function checkout_shipping_packing_script() { if ( ! is_checkout() ) return; // Only checkout page ?> <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'); console.log('response: '+result); // just for testing | TO BE REMOVED }, error: function(error){ console.log(error); // just for testing | TO BE REMOVED } }); }); }); </script> <?php } // Php Ajax (Receiving request and saving to WC session) add_action( 'wp_ajax_woo_get_ajax_data', 'woo_get_ajax_data' ); add_action( 'wp_ajax_nopriv_woo_get_ajax_data', 'woo_get_ajax_data' ); function woo_get_ajax_data() { if ( isset($_POST['packing']) ){ $packing = sanitize_key( $_POST['packing'] ); WC()->session->set('chosen_packing', $packing ); echo json_encode( $packing ); } die(); // Alway at the end (to avoid server error 500) }</code>
以上是如何根据 WooCommerce Checkout 中的单选按钮选择实施动态费用调整?的详细内容。更多信息请关注PHP中文网其他相关文章!