WC_Comments::get_review_counts_for_product_ids()
Utility function for getting review counts for multiple products in one query. This is not cached.
Method of the class: WC_Comments{}
No Hooks.
Return
Array
.
Usage
$result = WC_Comments::get_review_counts_for_product_ids( $product_ids );
- $product_ids(array) (required)
- Array of product IDs.
Changelog
Since 5.0.0 | Introduced. |
WC_Comments::get_review_counts_for_product_ids() WC Comments::get review counts for product ids code WC 9.4.2
public static function get_review_counts_for_product_ids( $product_ids ) { global $wpdb; if ( empty( $product_ids ) ) { return array(); } $product_id_string_placeholder = substr( str_repeat( ',%s', count( $product_ids ) ), 1 ); $review_counts = $wpdb->get_results( // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Ignored for allowing interpolation in IN query. $wpdb->prepare( " SELECT comment_post_ID as product_id, COUNT( comment_post_ID ) as review_count FROM $wpdb->comments WHERE comment_parent = 0 AND comment_post_ID IN ( $product_id_string_placeholder ) AND comment_approved = '1' AND comment_type in ( 'review', '', 'comment' ) GROUP BY product_id ", $product_ids ), // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared. ARRAY_A ); // Convert to key value pairs. $counts = array_replace( array_fill_keys( $product_ids, 0 ), array_column( $review_counts, 'review_count', 'product_id' ) ); return $counts; }