Daniel Acevedo
Daniel Acevedo

Reputation: 141

Retrieve variations and prices

I triying to make a custom view of WC products trough a shortcode. I was able to get the variations names but I don't know how to get the price for each individual variation.

In all documentation and other questions I only find how to display a max and min price.

$products = wc_get_products( $args );
echo '<div id="restorana-wrapper">';
echo '<h3>' . $category . '</h3>';
echo '<ul class="dish-section">';
	foreach ($products as $product) {
    echo '<a href="' . $product->add_to_cart_url() . '">';
        echo '<li><div class="dish-container">';
            echo '<div class="dish-header">';
                echo '<span class="dish-title">' . $product->get_title() . '</span>';
                echo '<span class="spacer"></span>';
		      // IF PRODUCT IS SIMPLE SHOW PRICE (THIS WORKS OK)
					if ($product->get_type() == "simple") {
					echo '<span class="dish-price">' . $product->get_price() . '</span>';
					}
          // IN PRODUCT IS VARIABLE SHOW PRICE (THIS DOESNT WORK)
					if ($product->get_type() == "variable") {
						foreach ($product->get_variation_attributes() as $variations) {
							foreach ($variations as $variation) {
								echo $variation->regular_price . " - " . $variation;
							}
						}
					}
		
		
		
            echo '</div>';
        echo '<p class="dish-description">' . $product->get_description() . '</p>';
        echo '</div></li>';
    echo '</a>';
	
}

Upvotes: 1

Views: 92

Answers (1)

Boris Di&#225;dus
Boris Di&#225;dus

Reputation: 106

Instead of foreach ($product->get_variation_attributes() as $variations) {...} block you can use:

    $variations     = wc_get_products(
        array(
            'status'  => array( 'private', 'publish' ),
            'type'    => 'variation',
            'parent'  => $product->ID,
            'limit'   => 0,
            'orderby' => array(
                'menu_order' => 'ASC',
                'ID'         => 'DESC',
            ),
            'return'  => 'objects',
        )
    );

    foreach ($variations as $variation) {
        //Treat $variation as a simple WC_Product.
        //So all methods like get_title() as get_price() will work

        echo $variation->get_price();
    }

Upvotes: 2

Related Questions