wordpress - 在循环外获取平均产品属性值评级(WooCommerce)
问题描述
下面的代码输出循环内所有产品的平均评分(通过短代码),如下所示:3.0 4.0 4.0 5.0
function iw_get_product_ratings_by_attribute_shortcode() {
// The Query
$query = new WP_Query( array(
'posts_per_page' => -1,
'tax_query' => array(
'relation'=>'AND',
array(
'taxonomy' => 'pa_merk',
'field' => 'slug',
'terms' => 'twins'
)
)
) );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$rating = get_post_meta( get_the_id(), '_wc_average_rating', true );
if ($rating != 0) { echo number_format((float)$rating, 1, '.', ''); }
}
/* Restore original Post Data */
wp_reset_postdata();
}
}
add_shortcode('iw_get_product_ratings_by_attribute', 'iw_get_product_ratings_by_attribute_shortcode');
我怎样才能得到这些数字的总体平均值?
换句话说:我想显示所有产品的平均评分(属性为“pa_merk”,值为“双胞胎”)
更新:下面的代码完成了工作:)
function iw_get_product_ratings_by_attribute_shortcode() {
// The Query
$query = new WP_Query( array(
'posts_per_page' => -1,
'tax_query' => array(
'relation'=>'AND',
array(
'taxonomy' => 'pa_merk',
'field' => 'slug',
'terms' => 'twins'
)
)
) );
// The Loop
if ( $query->have_posts() ) {
$ratingSum = 0;
$postsCount = 0;
while ( $query->have_posts() ) {
$query->the_post();
$rating = get_post_meta( get_the_id(), '_wc_average_rating', true );
if ($rating != 0) {
$postsCount++;
$ratingSum += $rating;
}
}
if ($ratingSum > 0 && $postsCount > 0) {
return $ratingSum / $postsCount; // todo do the rounding stuff
}
/* Restore original Post Data */
wp_reset_postdata();
}
}
add_shortcode('iw_get_product_ratings_by_attribute', 'iw_get_product_ratings_by_attribute_shortcode');
解决方案
试试这个:(现在无法测试,可能有语法错误,并且可能可以改进。随时编辑我的答案!)
if ( $query->have_posts() ) {
$ratingSum = 0;
$postsCount = 0;
while ( $query->have_posts() ) {
$query->the_post();
$postsCount++;
$rating = get_post_meta( get_the_id(), '_wc_average_rating', true );
$ratingSum += $rating;
if ($rating != 0) { echo number_format((float)$rating, 1, '.', ''); }
}
if ($ratingSum > 0 && $postsCount > 0) {
echo $ratingSum / $postsCount; // todo do the rounding stuff
}
/* Restore original Post Data */
wp_reset_postdata();
}
希望我理解正确。
推荐阅读
- javascript - 如何使用带有正则表达式搜索选项的填充
- signal-processing - 为什么 16QAM 的 BER 优于 32QAM
- flask - 如何使用 AWS 应用程序负载均衡器避免 access-control-allow-origin 标头错误
- tensorflow-federated - TFF :每个客户端都执行预训练函数而不是 build_federated_averaging_process
- swift - 如何在集合视图中快速创建具有倾斜效果的捕捉滑块?
- mysql - Attunity 零时间戳值插入 mySQL DB
- boost - 构建一个使用本地发行版的 boost 的 cmake 项目
- android - 将数据从 BottomSheetFragment 传递到前一个 Fragment
- c# - 将泛型类型提取到接口中
- installation - CVI 安装