亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是否有可能制定自定義價格?

是否有可能制定自定義價格?

PHP
忽然笑 2021-10-22 14:40:01
我在 Wordpress 上通過 WooCommerce 銷售禮品卡。我的客戶應該能夠自己設置禮品卡金額的值。我只能通過插件來做到這一點。是否有可能通過更改一些代碼或通過functions.php 來做到這一點?已安裝 Pimwick 禮品卡 Pro
查看完整描述

1 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

是的,但如果從沒有額外插件的全新 WooCommerce 安裝中執行此操作,這是一個相當復雜的過程。你需要做以下事情來實現它:

  1. 為產品添加自定義輸入字段以添加自定義價格

  2. 將該產品添加到購物車時,將自定義輸入字段中的數據保存到會話(購物車)

  3. 創建訂單時,將購物車元數據(上面在 #2 中創建)添加到訂單中

  4. 根據自定義價格元調整產品的成本(在上面的 #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 );

    }

}


查看完整回答
反對 回復 2021-10-22
  • 1 回答
  • 0 關注
  • 136 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號