doukeng7426 2018-07-31 19:50
浏览 167

根据woocommerce中的维度(面积)范围设置产品价格

I use WordPress and woocommerce for an eCommerce website. I would like to calculate dynamically the product according to its area(height X Width)

So the product price will be based conditionally on area ranges like:

  • if an area is between 1 (sq.ft.) to 5 (sq.ft.) price is 5$
  • if an area is between 6 (sq.ft.) to 10 (sq.ft.) price is 6$

Any help will be appreciated.

  • 写回答

1条回答 默认 最新

  • dqouryz3595 2018-08-01 04:57
    关注

    Try the following code example that will auto calculate the product price based on its area when product is saved in backend. You might have to do some adjustments on area calculation based on your measurements unit settings…

    The code:

    add_action( 'save_post', 'calculate_product_price_based_on_area', 20, 3 );
    function calculate_product_price_based_on_area( $post_id, $post, $update ) {
    
        if ( $post->post_type != 'product') return; // Only products
    
        // If this is an autosave, our form has not been submitted, so we don't want to do anything.
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            return $post_id;
    
        // Check the user's permissions.
        if ( ! current_user_can( 'edit_product', $post_id ) )
            return $post_id;
    
        // Product width and height
        $width  = isset($_POST['_width'])  ? (float) $_POST['_width']  : 0;
        $height = isset($_POST['_height']) ? (float) $_POST['_height'] : 0;
    
        if( $width > 0 && $height > 0 ){
            // Area calculation from product width and height
            $area = $width * $height;
    
            // Define the price conditionally based on area
            if( $area > 0 && $area <= 5 ){
                $price = 5;
            } elseif( $area > 5 && $area <= 10 ){
                $price = 6;
            }
    
            // Update the calculated product price
            if( isset($price) && $price > 0 ){
                // if product is not on sale
                if( $_POST['_sale_price'] != '' ){
                    // Update active price
                    update_post_meta( $post_id, '_price', $price );
                }
                // Update regular price
                update_post_meta( $post_id, '_regular_price', $price );
                wc_delete_product_transients( $post_id ); // Update product cache
            }
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法