Woocommerce price in loop displays on wrong item

2019-08-25 02:28发布

问题:

Following the guide here http://www.w3bdeveloper.com/how-to/how-to-get-regular-price-of-a-product-in-wordpress-woocommerce/

Using the following code to call the price inside the loop, the price is displaying the wrong price per item.

The first item has no price, the second item has the first items price, the third item has the second price and so on.

      <div class='price'>
        <?php echo $product->regular_price; ?>
      </div>

If I use <?php echo $product->get_price_html(); ?> it displays correctly, but I'd like to be able to display the sale price and the regular price separately. Also for some reason, if I use this code before the button code, I get a fatal error.

The loop code is as follows:

<div class='post'>

    <a class='oxy-post-image' href='<?php the_permalink(); ?>'>
          <div class='oxy-post-image-fixed-ratio' style='background-image: url(<?php echo get_the_post_thumbnail_url(); ?>);'></div>

          <div class='price-overlay'>
            <?php echo $product->regular_price; ?>
          </div>    
    </a>
    <div class='post-wrapper'>    
        <a class='oxy-post-title' href='<?php the_permalink(); ?>'><?php the_title(); ?></a>    
        <div class='oxy-post-meta'>

            <div class='cart-button'>
                <?php global $product; echo apply_filters( 'woocommerce_loop_add_to_cart_link',
                      sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="button %s product_type_%s">%s</a>',
                      esc_url( $product->add_to_cart_url() ),
                      esc_attr( $product->get_id() ),
                      esc_attr( $product->get_sku() ),
                      $product->is_purchasable() ? 'add_to_cart_button' : '',
                      esc_attr( $product->get_type() ),
                      esc_html( $product->add_to_cart_text() ) ),$product ); ?>
            </div>
            </div>    
    </div>    
</div>

A screenshot of the items in the loop:

回答1:

Try to declare global $product before using echo $product->regular_price; so :

<div class='price-overlay'>
        <?php global $product; echo $product->regular_price; ?>
</div>