【发布时间】:2020-09-08 15:27:39
【问题描述】:
在 WooCommerce 结帐中,我已成功添加自定义单选按钮。我想根据客户的选择设置动态费用。客户可以从自定义单选按钮中选择一个选项。
这是我的代码:
// Output the Custom field in check out
add_action( 'woocommerce_review_order_before_payment', 'checkout_radio_choice', 10,2);
function checkout_radio_choice(){
?>
<label for="custom_field">
<input type="radio" name="custom_field" checked="checked" value="option0">DECLINED <br />
<input type="radio" name="custom_field" value="option1">SIGNATURE <br />
<input type="radio" name="custom_field" value="option2">INSURANCE<br />
</label> <br />
<?php
}
// Stores the custom field value in Cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_field_data', 10, 2 );
function save_custom_product_field_data( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['custom_field'] ) ) {
$cart_item_data[ 'custom_field' ] = $_REQUEST['custom_field'];
// below statement make sure every add to cart action as unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'my_order_data', $_REQUEST['custom_field'] );
}
return $cart_item_data;
}
// Outuput custom Item value in Cart and Checkout pages
add_filter( 'woocommerce_get_item_data', 'output_custom_product_field_data', 10, 2 );
function output_custom_product_field_data( $cart_data, $cart_item ) {
if( !empty( $cart_data ) )
$custom_items = $cart_data;
if( isset( $cart_item['custom_field'] ) ) {
$custom_items[] = array(
'key' => __('Custom Item', 'woocommerce'),
'value' => $cart_item['custom_field'],
'display' => $cart_item['custom_field'],
);
}
return $custom_items;
}
// Dynamic fee
function WPE_checkout_radio_choice_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$radio = WC()->session->get( 'radio_chosen' );
if ( "option_1" == $radio ) {
$fee = 4;
}
elseif ( "option_2" == $radio ) {
$fee = ( ( wc_prices_include_tax() ? $cart->get_cart_contents_total() + $cart->get_cart_contents_tax() : $cart->get_cart_contents_total() ) * 0.027 + 4.00 );
}
$cart->add_fee( __('Protection', 'woocommerce'), $fee );-
}
但是“WPE_checkout_radio_choice_fee()”函数出了点问题,因为它不起作用。
如何根据 WooCommerce 中的结帐单选按钮选择添加动态费用?
【问题讨论】:
标签: php jquery wordpress woocommerce checkout