PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, April 10, 2022

[FIXED] Woocommerce Show default variation price

 April 10, 2022     variations, woocommerce, wordpress     No comments   

Issue

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


Solution

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


Answered By - Anders Gulbæk
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing