步骤1:- 您需要创建一些自定义隐藏字段来发送将显示在单个产品页面上的自定义数据。例如:-
add_action('woocommerce_before_add_to_cart_button', 'custom_data_hidden_fields');
function custom_data_hidden_fields() {
echo '<div class="imput_fields custom-imput-fields">
<label class="price_prod">price: <br><input type="text" id="price_prod" name="price_prod" value="" /></label>
<label class="quantity_prod">quantity: <br>
<select name="quantity_prod" id="quantity_prod">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</label>
</div><br>';
}
步骤2:- 现在完成后,您需要编写主要逻辑 将所有产品自定义字段保存到您的购物车项目数据,请按照以下代码操作。
// Logic to Save products custom fields values into the cart item data
add_action( 'woocommerce_add_cart_item_data', 'save_custom_data_hidden_fields', 10, 2 );
function save_custom_data_hidden_fields( $cart_item_data, $product_id ) {
$data = array();
if( isset( $_REQUEST['price_prod'] ) ) {
$cart_item_data['custom_data']['price_pro'] = $_REQUEST['price_prod'];
$data['price_pro'] = $_REQUEST['price_prod'];
}
if( isset( $_REQUEST['quantity_prod'] ) ) {
$cart_item_data['custom_data']['quantity'] = $_REQUEST['quantity_prod'];
$data['quantity'] = $_REQUEST['quantity_prod'];
}
// below statement make sure every add to cart action as unique line item
$cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'price_calculation', $data );
return $cart_item_data;
}
步骤3:您需要使用自定义计算覆盖商品价格。它将适用于单个产品会话的每个方案。
add_action( 'woocommerce_before_calculate_totals', 'add_custom_item_price', 10 );
function add_custom_item_price( $cart_object ) {
foreach ( $cart_object->get_cart() as $item_values ) {
## Get cart item data
$item_id = $item_values['data']->id; // Product ID
$original_price = $item_values['data']->price; // Product original price
## Get your custom fields values
$price1 = $item_values['custom_data']['price1'];
$quantity = $item_values['custom_data']['quantity'];
// CALCULATION FOR EACH ITEM:
## Make HERE your own calculation
$new_price = $price1 ;
## Set the new item price in cart
$item_values['data']->set_price($new_price);
}
}
一切都将在函数内完成.php
参考网站