简体   繁体   中英

Getting a WooCommerce Product Properties from WP_Query Loop

I have a function that uses WP_Query to loop through product post types. Within this function I can get things from the post object like permalink, the title, the image etc for the product post. However for each product in the loop and I need to access the product object because I want to calculate and display the review ratings. I was using global $product and then $product->get_rating_count() etc to get the data needed. However while debugging another bit of code I found the well known 'ID was called incorrectly. Product properties should not be accessed directly.' error for this function.

Everything still works (with debugging turned off), but I want to be sure that it still works in future versions of WooCommerce. Does anybody know I can from within a WP_Query loop (that is looping through the product post types) access the product object properties without this error?

Here is my code....

<?php
// Get the product rating
global $product;
if ( 'no' === get_option( 'woocommerce_enable_review_rating' ) ) {
return;
}
$rating_count = $product->get_rating_count();
$review_count = $product->get_review_count();
$average      = $product->get_average_rating();
if ( $rating_count > 0 ) : ?>
<div class="woocommerce-product-rating">
  <?php echo wc_get_rating_html( $average, $rating_count ); ?>
  <?php if ( comments_open() ) : ?>
  <a href="<?php echo get_permalink( $product->ID ); ?>#reviews" class="woocommerce-review-link" rel="nofollow">(
    <?php printf( _n( '%s customer review', '%s customer reviews', $review_count, 'woocommerce' ), '<span class="count">' . esc_html( $review_count ) . '</span>' ); ?>)
  </a>
  <?php endif ?>
</div>
<?php endif; ?>

Any help would be much appreciated! Cheers!

The $product variable is an instance of the WC_Product class which is different from the WP_Post class. You can read about the WC_Product API here:

https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html

The correct way to get the product ID in this case is using the get_id method:

$product->get_id()

I guess I needed some sleep....

After looking at this again this morning I can see something that for some reason I was glazing over before. I was calling $product->ID for the link of the product but of course it should now be $product->get_id(). With that change it is now working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM