1 回答
TA贡献1798条经验 获得超3个赞
你的代码有点过时了,有一些错误,还有很多遗漏的东西来得到你所期望的……
请尝试以下操作(更新):
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5 );
function custom_product_price_field(){
echo '<div class="custom-text text">
<p>'.__("Quantity of adults:").'</p>
<input type="text" name="qtty_adults" value="" title="'.__("Quantity Adults").'" class="qtty-field">
</div>
<div class="custom-text text">
<p>'.__("Quantity of children:").'</p>
<input type="text" name="qtty_kids" value="" title="'.__("Quantity Kids").'" class="qtty-field">
</div>';
}
// Add selected add-on option as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data_callback', 10, 3 );
function filter_add_cart_item_data_callback( $cart_item_data, $product_id, $variation_id ) {
if ( isset( $_POST['qtty_kids'] ) && $children_discount = get_field( 'children_discount', $product_id ) ) {
$cart_item_data['children_discount'] = (float) $children_discount - (float) sanitize_text_field( $_POST['qtty_kids'] );
$cart_item_data['unique_key'] = md5( microtime().rand() ); // Make each item unique
}
return $cart_item_data;
}
// Set a discount based a product custom field(s)
add_action('woocommerce_cart_calculate_fees' , 'add_children_discount', 10, 1 );
function add_children_discount( $cart ){
if ( is_admin() && ! defined('DOING_AJAX') )
return;
if ( did_action('woocommerce_cart_calculate_fees') >= 2 )
return;
$discount = 0; // Initialising
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
if( isset( $cart_item['children_discount'] ) ) {
$discount += $cart_item['children_discount'];
}
}
if ( $discount > 0 )
$cart->add_fee( __("Discount for children", "woocommerce"), -$discount );
}
测试和工作。
- 1 回答
- 0 关注
- 58 浏览
添加回答
举报