在Woocommerce中的WP_Query循环中显示产品价格

aMJ*_*Jay 4 php wordpress product woocommerce price

我有这段代码来显示某个类别的产品,我也想显示它的价格。有什么想法可以添加或更改吗?下面的代码不显示任何内容(也没有错误)。

<?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>
Run Code Online (Sandbox Code Playgroud)

另外,如果可能的话,我想从woocommerce画廊中获取第一张图片(而不是缩略图)。非常感谢。

Loi*_*tec 5

您应该替换以下行:

<p><?php echo $wc_query->get_price_html(get_the_ID()); ?></p>
Run Code Online (Sandbox Code Playgroud)

通过以下几行:

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

  • @ShahidKhattak使用`get_post_meta(get_the_ID(),'_regular_price',true);`和`get_post_meta(get_the_ID(),'_sale_price',true);` (3认同)