Thursday, 24 July 2014

Changing price range of Woocommerce composite products

Written by 
Changing price range of Woocommerce composite products

Recently when developing a Wordpress Woocommerce site I came across a problem.  Composite products display their price as a range, ie "£20 - £30".  This might not suit all stores, and for a recent client we decided to change it to the format "From £20".

This can be achieved without any hacking of core files, by using the Wordpress filter system.  Just add the code below into your child theme's functions.php file.

add_filter( 'woocommerce_composite_price_html', 'updated_composite_price_format', 10, 2 );
add_filter( 'woocommerce_composite_sale_price_html', 'updated_composite_price_format', 10, 2 );

function updated_composite_price_format( $price, $product ) {
    if ( $product->min_composite_price === '' ) {
        $price = apply_filters( 'woocommerce_composite_empty_price_html', '', $product );
    } else {        
        $prices = array( $product->min_composite_price, $product->max_composite_price );
        sort( $prices );
    
        if ( ! $product->contains_nyp )
            $price = $prices[0] !== $prices[1] ? 'From '.wc_price( $prices[0] ) : wc_price( $prices[0] );
        else
            $price = wc_price( $prices[0] );
            
        // Sale
        $prices = array( $product->min_composite_regular_price, $product->max_composite_regular_price );
        sort( $prices );

        if ( ! $product->contains_nyp )
            $saleprice = $prices[0] !== $prices[1] ? 'From '.wc_price( $prices[0] ) : wc_price( $prices[0] );
        else
            $saleprice = wc_price( $prices[0] );

        if ( $price !== $saleprice ) {
            $price = $product->contains_nyp ? sprintf( _x( '%1$s%2$s', 'Price range: from', 'woocommerce-composite-products' ), $product->get_price_html_from_text(), $product->get_price_html_from_to( $saleprice, $price ) . $product->get_price_suffix() ) : $product->get_price_html_from_to( $saleprice, $price ) . $product->get_price_suffix();
        } else {
            $price = $product->contains_nyp ? sprintf( _x( '%1$s%2$s', 'Price range: from', 'woocommerce-composite-products' ), $product->get_price_html_from_text(), $price . $product->get_price_suffix() ) : $price . $product->get_price_suffix();
        }
    }
    return $price;
}

Read 6349 times Last modified on Monday, 13 November 2017 12:20
Alex

Alex is the founder / owner of Freshpage Web Design and has a wealth of experience across all levels of web development, including Java, SQL, HTML, CSS, PHP as well as content management systems such as Wordpress, Joomla and Magento.