Woocommerce - Display calculated price by weight in variable product

Viewed 116

I am building a simple ecommerce site with WordPress and WooCommerce. There wasn't enough time to build a custom platform, yet still, I know that editing the theme's functions.php file I can tweak some stuff. At the moment, I added the following code, which will take the lowest price and display it in the product's label:

add_filter('woocommerce_variable_sale_price_html', 'lw_variable_product_price', 10, 2);
add_filter('woocommerce_variable_price_html', 'lw_variable_product_price', 10, 2);
function lw_variable_product_price($v_price, $v_product)
{

    $prod_prices = array(
        $v_product->get_variation_price('min', true) ,
        $v_product->get_variation_price('max', true) ,
    );
    $prod_price = $prod_prices[0] !== $prod_prices[1] ? sprintf(__('<span>Approximate price per pound: </span> %1$s', 'woocommerce') , wc_price($prod_prices[0])) : wc_price($prod_prices[0]);

    return $prod_price;
}

However, since the products that will be sold are weight-based, I need to display, let's say, the result of

$prod_prices = array(
    $v_product->get_variation_price('max', true) ,
    $v_product->get_variation_weight('max', true) ,
);
$prod_price = $prod_prices[0] / $prod_prices[1]; //calculated price.

How can I do this? I tried with

$prod_price = $prod_prices[0] / $prod_prices[1] ? sprintf(__('<span>Approximate price per pound: </span> %1$s', 'woocommerce') , wc_price($prod_prices[0])) : wc_price($prod_prices[0]);

but it won't work.

1 Answers

If you want to calculate the approximate price based on weight using the maximum variable product price you can use the following function:

add_filter( 'woocommerce_variable_sale_price_html', 'lw_variable_product_price', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'lw_variable_product_price', 10, 2 );
function lw_variable_product_price( $price, $product ) {

    // get the maximum price of the variable product
    $max    = $product->get_variation_price('max');
    // get the weight of the variable product
    $weight = $product->get_weight();

    $new_price = '';
    if ( $max && $weight ) {
        $new_price = sprintf( __( '<span>Approximate price per pound: </span> %1$s', 'woocommerce' ) , wc_price( $max / $weight ) );
    }
    
    return $new_price;
}

The code has been tested and works. Add it to your active theme's functions.php.

Related