显示Woocommerce中客户的特定产品的总购买数量 [英] Display the total purchase count of a specific product for customer in Woocommerce
问题描述
在Woocommerce中,我想在与当前客户产品不同的页面上显示特定产品的总数.
In Woocommerce, I would like to show total count of a specific product on a different page than the product for the current customer.
所以我试图从该线程更改答案代码:
当前用户按产品购买的总次数在Woocommerce中
So I have tryied to change the answer code from this thread:
Total purchase count by product for current user in Woocommerce
但是我不知道如何设置产品ID,因为该函数正在使用全局变量product.
But I don't know how to set the product ID as the function is using the global variable product.
感谢您的帮助
推荐答案
您只需对以下功能进行一些更改:
You just nee to make a very little change in the function like:
function wc_product_sold_count( $product_id ) {
// Only for logged in users
if ( ! is_user_logged_in() ) return; // Exit for non logged users
$user_id = get_current_user_id(); // Current User ID
// The SQL request
$units_bought = $wpdb->get_var( "
SELECT SUM(woim2.meta_value)
FROM {$wpdb->prefix}woocommerce_order_items AS woi
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta woim ON woi.order_item_id = woim.order_item_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta woim2 ON woi.order_item_id = woim2.order_item_id
INNER JOIN {$wpdb->prefix}postmeta pm ON woi.order_id = pm.post_id
INNER JOIN {$wpdb->prefix}posts AS p ON woi.order_id = p.ID
WHERE woi.order_item_type LIKE 'line_item'
AND p.post_type LIKE 'shop_order'
AND p.post_status IN ('wc-completed','wc-processing')
AND pm.meta_key = '_customer_user'
AND pm.meta_value = '$user_id'
AND woim.meta_key = '_product_id'
AND woim.meta_value = '$product_id'
AND woim2.meta_key = '_qty'
");
// Display count if is greater than zero
if( $units_bought > 0 ){
$label = __( 'Units bought' , 'woocommerce' ); // Label
// Returned output
return '<p class="units-bought"><strong>' . $label . ': </strong>' . $units_bought . '</p>';
}
}
// The shortcode from this function
add_shortcode('product_sold_count', 'shortcode_product_sold_count');
function shortcode_product_sold_count( $atts ) {
$atts = shortcode_atts( array(
'id' => '',
), $atts, 'product_sold_count' );
return wc_product_sold_count( $atts['id'] );
}
代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.
Code goes in function.php file of your active child theme (or active theme). Tested and works.
用法示例:
1)作为Wordpress文本编辑器页面中的简码(用产品ID替换 37
):
1) As a shortcode in a page in the Wordpress Text Editor (replace 37
by your product ID):
[product_sold_count id="37"]
2)在任何php代码中(用您的产品ID替换 37
):
2) In any php code (replace 37
by your product ID):
echo wc_product_sold_count( 37 );
这篇关于显示Woocommerce中客户的特定产品的总购买数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!