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'] );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
USAGE Examples:
1) As a shortcode in a page in the Wordpress Text Editor (replace 37
by your product ID):
[product_sold_count id="37"]
2) In any php code (replace 37
by your product ID):
echo wc_product_sold_count( 37 );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…