Search code examples
phpwordpresswoocommercearea

Set product prices based on a range of their dimensions (area) in 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.


Solution

  • 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.