在Woocommerce中,我试图以以下方式显示每个产品的报告(HTML表):
基于“ Display total customers reviews and ratings average in WooCommerce” 答案代码,它以这种方式获取产品平均评分:
echo products_rating_average_html();
我如何才能分别获得每个产品的平均评分……例如,如果该产品有4或5条评论,则可以获得它们的平均评分(针对每个产品)
我也希望对每种产品都发表评论评论,并将它们放在表格中……
答案 0 :(得分:1)
这将给出给定产品ID的平均评分
$rating = get_post_meta( $product_id, '_wc_average_rating', true );
您可以在产品循环中使用此功能,这将为您提供不带任何html的原始平均评级
要获取最新评论,您可以在下面使用此代码在functions.php中添加,然后在要显示最新评论的地方调用此操作,将当前产品对象作为参数
function display_product_review($product_id) {
$product = wc_get_product( $product_id );
$comments = get_approved_comments( $product->id );
$product_link = '/product/' . $product->post->post_name . "/#tab-reviews/";
if ( !empty ($comments) ) {
echo $comments[0]->comment_content . '<br><a href="'. $product_link . '">Read more reviews...</a>';
} else {
echo "There are no reviews for this product yet. Would you like to <a href='" . $product_link ."'>add your own review</a>?";
}
}
add_action('get_latest_review','display_product_review');
呼吁采取行动
do_action('get_latest_review',$product);
答案 1 :(得分:1)
看看this answer thread,您会发现可以使用WC_Product
这样的方法:
get_average_rating()
get_rating_counts()
…这是一个完整的示例:
1)获取产品所需的相关数据(可自定义):
$products_data = []; // Initializing
$products = wc_get_products( ['limit' => -1] ); // Get all WC_Product objects
// Loop through products -- Preparing data to be displayed
foreach ( $products as $product ) {
$product_id = $product->get_id();
// 1. Product data as product name …
$products_data[$product_id]['name'] = $product->get_name();
// 2. Average rating and rating count
$products_data[$product_id]['rating'] = (float) $product->get_average_rating();
$products_data[$product_id]['count'] = (int) $product->get_rating_count();
// 3. Reviews -- Loop though product reviews
foreach( get_approved_comments( $product_id ) as $review ) {
if( $review->comment_type === 'review' ) {
$products_data[$product_id]['reviews'][] = (object) [
'author' => $review->comment_author,
'email' => $review->comment_author_email,
'date' => strtotime($review->comment_date),
'content' => $review->comment_content,
];
}
}
}
2)在表中可自定义显示:
echo '<table class="products-reviews-ratings"><tr>
<th>'.__("ID").'</th>
<th>'.__("Name").'</th>
<th>'.__("Rating").'</th>
<th>'.__("count").'</th>
<th style="text-align:center">'.__("Reviews (author, date and content)").'</th>
</tr>';
foreach ($products_data as $product_id => $data){
echo '<tr>
<td>'.$product_id.'</td>
<td>'.$data['name'].'</td>
<td>'.$data['rating'].'</td>
<td>'.$data['count'].'</td>
<td style="text-align:center">';
if( isset($data['reviews']) && $data['reviews'] > 0 ) {
echo '<table>';
// Loop through reviews
foreach ($data['reviews'] as $review ){
echo '<tr>
<td><a href="mailto:'.$review->email.'">'.$review->author.'</a></td>
<td>'.date( 'Y-m-d', $review->date ).'</td>
<td>'.$review->content.'</td>
</tr>';
}
echo '</table>';
} else {
_e('No reviews yet');
}
echo '</td></tr>';
}
echo '</table>';
您将得到类似的东西: