如何在 WooCommerce 中获得最畅销的产品类别 ID? [英] How to get best selling product category IDs in WooCommerce?
本文介绍了如何在 WooCommerce 中获得最畅销的产品类别 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找展示 6 个最畅销产品类别的方法.这就是我现在得到的:
I looking for way to display the 6 best selling product categories. this is what i got now:
$termsprent = get_terms(
array(
'taxonomy' => 'product_cat',
'hide_empty' => true,
'numberposts' => 4,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'order' => 'desc',
)
);
有没有人知道修改它的方法,以便显示最畅销的产品类别?
does anyone knows a way to modify it so it will display the top selling product categories?
推荐答案
获取某个产品类别的总销售额
您可以使用以下函数获取属于特定产品类别的产品的总销售额.
该函数的唯一参数是产品类别 ID(term_id)
// gets the total sales count of a specific product category
function counts_total_sales_by_product_category( $term_id ) {
global $wpdb;
$total_sales = $wpdb->get_var("
SELECT sum(meta_value)
FROM $wpdb->postmeta
INNER JOIN {$wpdb->term_relationships} ON ( {$wpdb->term_relationships}.object_id = {$wpdb->postmeta}.post_id )
WHERE ( {$wpdb->term_relationships}.term_taxonomy_id IN ($term_id) )
AND {$wpdb->postmeta}.meta_key = 'total_sales'"
);
return $total_sales;
}
获得最畅销的产品类别
以下函数将返回一个数组,其中最畅销的产品类别按降序排列.
该函数唯一的参数是产品类别的限制被退回.
// gets the n product categories with the best sales
function gets_best_selling_product_categories( $limit ) {
$total_sales = array();
$product_categories = get_terms( 'product_cat' );
foreach ( $product_categories as $product_cat ) {
$product_cat_id = $product_cat->term_id;
$total_sales[$product_cat_id] = counts_total_sales_by_product_category( $product_cat_id );
}
// removes empty values from the array
$total_sales = array_filter( $total_sales );
// sorts the array values in descending order
arsort( $total_sales );
// gets the first n ($limit) product categories with the most sales
$best_product_categories = array_slice( $total_sales, 0, $limit, true );
return $best_product_categories;
}
结果
下面是gets_best_sales_product_categories(4);
函数的var_dump()
的结果:
array(4) {
[15]=> string(3) "209"
[30]=> string(3) "160"
[32]=> string(2) "56"
[31]=> string(2) "18"
}
数组 key 将是产品类别 ID,其值是该类别的总销售额.
The array key will be the product category id and its value is the total sum of sales for that category.
代码已经过测试并且可以工作.将它添加到您的活动主题的functions.php.
这篇关于如何在 WooCommerce 中获得最畅销的产品类别 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文