Getting WC price line inside a WP_Query loop

I am traversing the return of a WP_Query on Woocommerce products and I need to get the price line preferably using to inherit WC function


Two solutions have been offered the first one:

$price = get_post_meta( get_the_ID(), '_regular_price', true);

I tested and it is working but needs some efforts cause I need to extract the sale price and sanitize the output.

The other solution:

$_product = wc_get_product( $pid ); //for the $pid I put the_ID(), should have put get_the_ID()
$pricenew = $_product->get_price_html();

I got the following error:

Fatal error: Uncaught Error: Call to a member function

Later I figured that to avoid the error I should have put get_the_ID, the_ID echoes out the post id but get_the_ID returns it.

As suggested per another post on StackOverflow I tried putting a

  have_posts() ) : 
    while ( $query->have_posts() ) : $query->the_post(); 
    	global $product; 
        echo  $product->get_price_html();

And yes, it did work.

Leave a Reply

Your email address will not be published. Required fields are marked *