0

I have used the below code to show the default variation price on the products page instead of the price range.

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);

}

The problem is when then products are sorted by price, it uses the lowest variation price instead of the default. How can I set it so when sorting by price uses the default variation price instead?

1

get_variation_default_attributes and woocommerce_price are depreciated.

This works for me. If I have set default attributes.

function custom_variation_price( $price, $product ) {
    foreach($product->get_available_variations() as $pav){
        $def=true;
        foreach($product->get_default_attributes() as $defkey=>$defval){
            if($pav['attributes']['attribute_'.$defkey]!=$defval){
                $def=false;             
            }   
        }
        if($def){
            $price = $pav['display_price'];         
        }
    }   
    return wc_price($price);
}
2
  • Hi, I tried replacing my code with this and it is now showing the variation range for the price instead of the default variation. It also has not changed the sort order, e.g. sorting my lowest to highest still uses the lowest variation instead of the default value. – Jalapeno Jack Mar 24 '20 at 7:08
  • Do you have a default variation set? Which version of WooCommerce are you using? – Howard E Mar 24 '20 at 20:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.