gpt4 book ai didi

php - 在自定义 WooCommerce 报告中获取产品评论平均评级

转载 作者:行者123 更新时间:2023-12-03 08:55:36 24 4
gpt4 key购买 nike

在 Woocommerce 中,我尝试显示每个产品的报告(HTML 表),如下所示:

enter image description here

基于"Display total customers reviews and ratings average in WooCommerce "答案代码,以这种方式获取产品平均评分:

echo products_rating_average_html();

如何才能单独获得每个产品的平均评分...例如,如果产品有 4 或 5 条评论,则它会获得它们的平均评分(对于每个产品)

我还想获得每个产品的评论评论,以便将它们也放入表格中......

最佳答案

看看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>';

你会得到类似的东西:

enter image description here

关于php - 在自定义 WooCommerce 报告中获取产品评论平均评级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55629753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com