首頁  >  問答  >  主體

在 WooCommerce 中根據重量變更簡單產品的輸入數量步驟值

<p>我希望數量選擇器值會根據我們在「運送」>「產品重量」中為簡單產品設定的重量進行更改。 如下圖所示,當我們將產品的重量設定為0.5公斤時,產品數量選擇器從0.5開始,如果我們設定為1公斤,則從1開始。最後當我們將重量設為每個數字時,數量選擇器應該根據我們定義的權重數字啟動。 我修改了程式碼,但它不適用於小於 1 的值。 </p> <pre class="brush:php;toolbar:false;">/*Quantity Selector Based On Simple*/ function custom_quantity_selector_min_value( $min, $product ) { $weight = $product->get_weight(); if ( $weight > 0 ) { $min = $weight; } return $min; } add_filter( 'woocommerce_quantity_input_min', 'custom_quantity_selector_min_value', 10, 2 ); //Modify the quantity selector step value. function custom_quantity_selector_step( $step, $product ) { $weight = $product->get_weight(); if ( $weight > 0 ) { $step = $weight; } return $step; } add_filter( 'woocommerce_quantity_input_step', 'custom_quantity_selector_step', 10, 2 ); //Update the quantity selector value dynamically. function custom_quantity_selector_value( $input_value, $product ) { $weight = $product->get_weight(); if ( $weight > 0 ) { $input_value = $weight; } return $input_value; } add_filter( 'woocommerce_quantity_input_value', 'custom_quantity_selector_value', 10, 2 );</pre></p>
P粉351138462P粉351138462381 天前505

全部回覆(1)我來回復

  • P粉613735289

    P粉6137352892023-09-05 13:56:13

    要使用的正確程式碼替換(更新):

    • 簡單的產品,
    • 或可變產品(及其變體)。

    它將如預期般順利工作:

    • 單一產品頁面,
    • 還有購物車頁面。
    add_filter( 'woocommerce_quantity_input_args', 'cart_variation_quantity_input_args', 10, 2 );
    function cart_variation_quantity_input_args( $args, $product ){
        $product_weight = $product->get_weight();
        
        if( $product_weight > 0 ) {
            if ( ! is_cart()) {
                $args['input_value'] = $product_weight;
            } 
            $args['step'] = $args['min_value'] = $product_weight;
        }
        return $args;
    }
    

    請確保您也新增了(用於庫存管理):

    remove_filter('woocommerce_stock_amount', 'intval');
    add_filter('woocommerce_stock_amount', 'floatval');
    

    程式碼位於活動子主題(或活動主題)的functions.php 檔案中。經過測試並有效。


    載入包含 0.5 重量的產品的頁面時:

    在產品上設定正確的數量輸入,並以 0.5 的步長增加(正常步長也是 1)

    在購物車頁面上,一切都如預期進行,步長為 0.5(正常步長也是 1)

    相關(針對變體):根據 WooCommerce 中選定的變化權重變更輸入數量步驟值

    回覆
    0
  • 取消回覆