get_rating_count(), (float) $product->get_average_rating() ); } /** * The same pair read from WooCommerce's own rating meta, for callers * that hold a raw post row instead of a WC_Product. * * @param int $product_id Product ID. * @return array{rating?: float, rating_count?: int} */ public static function forProductId( int $product_id ): array { if ( ! self::enabled() ) { return array(); } $counts = get_post_meta( $product_id, '_wc_rating_count', true ); $count = is_array( $counts ) ? (int) array_sum( array_map( 'intval', $counts ) ) : 0; return self::pair( $count, (float) get_post_meta( $product_id, '_wc_average_rating', true ) ); } /** * @return bool Whether the store shows product ratings at all. */ private static function enabled(): bool { return function_exists( 'wc_review_ratings_enabled' ) && wc_review_ratings_enabled(); } /** * @param int $count Number of ratings. * @param float $average Average rating. * @return array{rating?: float, rating_count?: int} */ private static function pair( int $count, float $average ): array { if ( $count < 1 || $average <= 0 ) { return array(); } return array( 'rating' => round( $average, 1 ), 'rating_count' => $count, ); } }