skip to Main Content

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!

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search