Amrita Deb
Amrita Deb

Reputation: 335

Get and display the variable product price range in Woocommerce 3

I am very new to wordpress and woocommerce. I am modifying the twenty seventeen theme's search result page to look like a table. Most of the products are variable products.I am using the code as below to show the results in a table

    <table class="search-res" style="table-layout: auto; width: 100%;">
            <tr><td>
            <?php
            if ( has_post_thumbnail()) 
                the_post_thumbnail('excerpt-thumb');        
                ?></td>
                <td>
                    <?php 
                    the_title( sprintf( '<th class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ) );
                    echo"</a></th>";
                    ?>
                </td>
                <td style="font-style:italic;font-size:small;"><?php the_excerpt(); ?></td>
            <th><?php 
                global $post;
   $product = new WC_Product($post->ID ); 
  echo wc_price($product->get_price_including_tax(1,$product->get_price()));
?></th>
            </tr>

        </table>

The problem that I am facing is here the minimum price of the product is gettiong displayed. Instead I want the price range to show up. Also how can I get rating and category attributes of the product to show up in the table?

Upvotes: 3

Views: 9312

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253784

You just need to use the WC_Product_Variable get_price_html() method that will do it for you:

<?php
global $post;

// Get the WC_Product_Variable instance Object
$product = wc_get_product( $post->ID ); // Works for any product type

// Displaying the formatted "Min" - "Max" price range
echo $product->get_price_html();
?>

Tested and works

Upvotes: 4

Amrita Deb
Amrita Deb

Reputation: 335

Figured it out. Not the ideal way to do it and I am certain there is an easier way to do things but still, here's my workaround:

 <?php
                global $post;
$parent_product=new WC_Product_Variable($post->ID);
$variations=$parent_product->get_children();
$max_price=0;
$min_price=10000;
foreach ($variations as $product){
        $single_variation=new WC_Product_Variation($product);
        if($single_variation->price > $max_price){
            $max_price=$single_variation->price;
        }
    if($single_variation->price < $min_price){
            $min_price=$single_variation->price;
        }

}
                    echo get_woocommerce_currency_symbol().$min_price.'-'.get_woocommerce_currency_symbol().$max_price; 
                ?>

Upvotes: 0

Related Questions