Search code examples
phpwordpresswoocommercehook-woocommerce

WooCommerce variable products: Display the min price with a custom text for different prices


I'm setting up a function for Woocommerce that display discount price and the regular price for variable product, this function add a " from to " text before the price range.

The "WooCommerce variable products: keep only "min" price with a custom label" answer thread matches the best with what I am looking for and work like a charm!

But when all variations in a variable product have the same prices, the " start from " should not be displayed.

So I've made a simple try and add below the "if" condition

else {
    $price = sprintf( __( '%1$s', 'woocommerce' ), $min_price_html );
return $price;
}

and integrate in the if condition:

$price = sprintf( __( 'À partir de %1$s', 'woocommerce' ), $min_price_html );
    return $price; 

But it doesn't really work. Some help is appreciated and welcome.


Solution

  • To handle when all variations of a variable product are the same, you need to use array_unique() php function and count() to look if all variation prices are the same.

    So the code will be slightly different:

    add_filter( 'woocommerce_variable_price_html', 'custom_min_max_variable_price_html', 10, 2 );
    function custom_min_max_variable_price_html( $price, $product ) {
        $prices = $product->get_variation_prices( true );
        $count  = (int) count( array_unique( $prices['price'] ));
    
        // When all variations prices are the same
        if( $count === 1 )
            return $price;
    
        $min_price = current( $prices['price'] );
        $min_keys  = current(array_keys( $prices['price'] ));
    
        $min_reg_price  = $prices['regular_price'][$min_keys];
        $min_price_html = wc_price( $min_price ) . $product->get_price_suffix();
    
        // When min price is on sale (Can be removed)
        if( $min_reg_price != $min_price ) {
            $min_price_reg_html = '<del>' . wc_price( $min_reg_price ) . $product->get_price_suffix() . '</del>';
            $min_price_html = $min_price_reg_html .'<ins>' . $min_price_html . '</ins>';
        }
        $price = sprintf( __( 'À partir de %s', 'woocommerce' ), $min_price_html );
    
        return $price;
    }
    

    Code goes in functions.php file of your active child theme (or theme) or also in any plugin file.