在Woocommerce中,我想在不同于当前客户产品的页面上显示特定产品的总数。
所以我试图从该线程更改答案代码:
Total purchase count by product for current user in Woocommerce
但是我不知道如何设置产品ID,因为该函数正在使用全局变量product。
感谢您的帮助
答案 0 :(得分:0)
您只需对以下功能进行一些更改:
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文件中。经过测试,可以正常工作。
用法示例:
1)作为Wordpress文本编辑器中页面中的简码(用产品ID替换37
):
[product_sold_count id="37"]
2)在任何php代码中(用产品ID替换37
):
echo wc_product_sold_count( 37 );