Display the product price in a WP_Query loop in Woocommerce

aMJay picture aMJay · Jun 11, 2018 · Viewed 14.1k times · Source

I have this code to display products from a category and I would like to also display it's price. Any ideas what I could add or change? The code below doesn't display anything (no errors either).

<?php

$product_categories = array('cat-name');

$wc_query = new WP_Query( array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => 10,
    'tax_query' => array( array(
        'taxonomy' => 'product_cat',
        'field'    => 'slug',
        'terms'    => $product_categories,
        'operator' => 'IN',
    ) )
) );
?>
<h1 style="margin-top:30px;">Cat Name</h1>
<div class="changing-img">
     <?php if ($wc_query->have_posts()) : ?>
     <?php while ($wc_query->have_posts()) :
                $wc_query->the_post(); ?>
<a href="<?php the_permalink(); ?>">
          <?php the_post_thumbnail('full'); ?>
          <?php the_post_thumbnail('full'); ?>
          <h6><?php the_title(); ?> </h6>
          <p><?php echo $wc_query->get_price_html(get_the_ID()); ?></p>
</a>
     <?php endwhile; ?>
     <?php wp_reset_postdata(); ?>
     <?php else:  ?>
     <li>
          <?php _e( 'No products' ); ?>
     </li>
     <?php endif; ?>
</div>

Also, if that would be possible I'd like to pull a first image from a woocommerce gallery (not a thumbnail). Thanks a lot.

Answer

LoicTheAztec picture LoicTheAztec · Jun 12, 2018

August 2020 Update

You should need to replace the line:

<p><?php echo $wc_query->get_price_html(get_the_ID()); ?></p>

By the following lines:

<?php $price = get_post_meta( get_the_ID(), '_price', true ); ?>
<p><?php echo wc_price( $price ); ?></p>

Or by this much better way (that will output the correct formatted price for display):

<?php $product = wc_get_product( get_the_ID() ); /* get the WC_Product Object */ ?>
<p><?php echo $product->get_price_html(); ?></p>