Or *_*rtz 1 wordpress woocommerce
我正在寻找显示 6 个最畅销产品类别的方法。这就是我现在得到的:
$termsprent = get_terms(
array(
'taxonomy' => 'product_cat',
'hide_empty' => true,
'numberposts' => 4,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'order' => 'desc',
)
);
Run Code Online (Sandbox Code Playgroud)
有谁知道如何修改它以显示最畅销的产品类别?
获取产品类别的销售总额
您可以使用以下函数获取属于特定产品类别的产品的销售额总和。
该函数的唯一参数是产品类别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;
}
Run Code Online (Sandbox Code Playgroud)
获取最畅销的产品类别
以下函数将返回一个数组,其中最畅销的产品类别按降序排列。
该函数的唯一参数是要返回的产品类别的限制。
// 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;
}
Run Code Online (Sandbox Code Playgroud)
结果
var_dump()下面是该函数的结果gets_best_selling_product_categories( 4 );:
array(4) {
[15]=> string(3) "209"
[30]=> string(3) "160"
[32]=> string(2) "56"
[31]=> string(2) "18"
}
Run Code Online (Sandbox Code Playgroud)
数组键是产品类别 ID,其值是该类别的销售额总和。
该代码已经过测试并且可以工作。将其添加到活动主题的functions.php中。
| 归档时间: |
|
| 查看次数: |
837 次 |
| 最近记录: |