5
votes

I'm using Woocommerce and product variations and all my variations have a default variation defined. I would like to know, how I can find the default variation and display it's price.

This is the code I got so far, but it displays the cheapest variation price, and I'm looking for my default variation product price instead.

// Use WC 2.0 variable price format, now include sale price strikeout
add_filter( 'woocommerce_variable_sale_price_html', 'wc_wc20_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'wc_wc20_variation_price_format', 10, 2 );
function wc_wc20_variation_price_format( $price, $product ) {
// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice ) {
    $price = '<del>' . $saleprice . '</del> <ins>' . $price . '</ins>';
}
return $price;

}

I found the code example here Woocommerce variation product price to show default

2

2 Answers

7
votes

I did not find answer for this question (how to display price from default product variation instead of price range?) so i created the code:

add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);

    function custom_variation_price( $price, $product ) {

        foreach($product->get_available_variations() as $pav){
            $def=true;
            foreach($product->get_variation_default_attributes() as $defkey=>$defval){
                if($pav['attributes']['attribute_'.$defkey]!=$defval){
                    $def=false;             
                }   
            }
            if($def){
                $price = $pav['display_price'];         
            }
        }   

        return woocommerce_price($price);

    }

This plugin show price from default variation, of course if you set default values before. Tested on woocommerce version 2.6.2.

0
votes

This is my own solution, think it could be better, but I'm not a php developer, so feel free to add improvements.

function wc_wc20_variation_price_format( $price, $product ) {
// Main Price
$available_variations = $product->get_available_variations();
$selectedPrice = '';

foreach ( $available_variations as $variation )
{
    $tmp = implode($variation['attributes']);

    if (strpos($tmp,'standard') !== false) {
        $selectedproduct = wc_get_product($variation['variation_id']);
        $price =  $selectedproduct->get_price();
        $selectedPrice = wc_price($price);
    }       
}

return $selectedPrice;
}