1 回答

TA貢獻1951條經驗 獲得超3個贊
是的,但如果從沒有額外插件的全新 WooCommerce 安裝中執行此操作,這是一個相當復雜的過程。你需要做以下事情來實現它:
為產品添加自定義輸入字段以添加自定義價格
將該產品添加到購物車時,將自定義輸入字段中的數據保存到會話(購物車)
創建訂單時,將購物車元數據(上面在 #2 中創建)添加到訂單中
根據自定義價格元調整產品的成本(在上面的 #3 中添加)。
第 1 步:添加自定義輸入字段:
您可以使用woocommerce_before_add_to_cart_button
過濾器添加輸入字段,如下所示。
或者,您可以使用woocommerce_wp_text_input
-這是一個示例。
add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_price_input', 100 );
function add_custom_price_input() {
if(get_the_ID() != 123) { //use the product ID of your gift card here, otherwise all products will get this additional field
return;
}
echo '<input type="number" min="50" placeholder="50" name="so_57140247_price">';
}
第 2 步:將自定義價格保存到購物車/會話
接下來,我們需要確保您的自定義輸入字段數據被轉移到購物車/會話數據。我們可以使用woocommerce_add_cart_item_data
( docs | example )過濾器:
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_meta_to_cart', 10, 3 );
function add_custom_meta_to_cart( $cart_item_data, $product_id, $variation_id ) {
$custom_price = intval(filter_input( INPUT_POST, 'so_57140247_price' ));
if ( !empty( $custom_price ) && $product_id == 123 ) { //check that the custom_price variable is set, and that the product is your gift card
$cart_item_data['so_57140247_price'] = $custom_price; //this will add your custom price data to the cart item data
}
return $cart_item_data;
}
第 3 步:將購物車元添加到訂單中
接下來,我們必須將購物車/會話中的元添加到訂單本身,以便它可以用于訂單總額計算。我們使用woocommerce_checkout_create_order_line_item
( docs | example )來做到這一點:
add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_meta_to_order', 10, 4 );
function add_custom_meta_to_order( $item, $cart_item_key, $values, $order ) {
//check if our custom meta was set on the line item of inside the cart/session
if ( !empty( $values['so_57140247_price'] ) ) {
$item->add_meta_data( '_custom_price', $values['so_57140247_price'] ); //add the value to order line item
}
return;
}
第 4 步:調整禮品卡訂單項的總數
最后,我們根據輸入字段中輸入的值簡單地調整禮品卡行項目的成本。我們可以掛鉤woocommerce_before_calculate_totals
(docs | example)來做到這一點。
add_action( 'woocommerce_before_calculate_totals', 'calculate_cost_custom', 10, 1);
function calculate_cost_custom( $cart_obj ) {
foreach ( $cart_obj->get_cart() as $key => $value ) {
$price = intval($value['_custom_price']);
$value['data']->set_price( $price );
}
}
- 1 回答
- 0 關注
- 136 瀏覽
添加回答
舉報