我正在尝试找出一个函数,该函数可获取当前用户所有已下订单中所购买商品的总数(不是总数,而是商品)。到目前为止,我已经发现了这一点(不起作用)-但是,此函数应该再次获得总计,而不是项。一直在尝试对其进行编辑,但到目前为止没有成功。
public function get_customer_total_order() {
$customer_orders = get_posts( array(
'numberposts' => - 1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => array( 'shop_order' ),
'post_status' => array( 'wc-completed' )
) );
$total = 0;
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order );
$total += $order->get_total();
}
return $total;
}
有什么想法吗?
答案 0 :(得分:3)
更新 (考虑物料数量)
以下非常轻巧的功能将获得客户购买的商品总数:
function get_user_total_purchased_items( $user_id = 0 ){
global $wpdb;
$customer_id = $user_id === 0 ? get_current_user_id() : (int) $user_id;
return (int) $wpdb->get_var( "
SELECT SUM(woim.meta_value)
FROM {$wpdb->prefix}woocommerce_order_items AS woi
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
INNER JOIN {$wpdb->prefix}posts as p ON woi.order_id = p.ID
INNER JOIN {$wpdb->prefix}postmeta as pm ON woi.order_id = pm.post_id
WHERE woi.order_item_type = 'line_item'
AND p.post_type LIKE 'shop_order'
AND p.post_status IN ('wc-completed')
AND pm.meta_key LIKE '_customer_user'
AND pm.meta_value LIKE '$customer_id'
AND woim.meta_key LIKE '_qty'
" );
}
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。
用法示例
1)显示当前用户购买的商品总数:
<?php echo '<p>Total purchased items: ' . get_user_total_purchased_items() . '</p>'; ?>
2)显示给定用户ID的已购买商品总数:
// Here the user ID is 105
<?php echo '<p>Total purchased items: ' . get_user_total_purchased_items(105) . '</p>'; ?>
答案 1 :(得分:-1)
请尝试以下代码
global $wpdb;
$customer_orders = get_posts( array(
'numberposts' => - 1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => array( 'shop_order' ),
'post_status' => array( 'wc-completed' )
) );
$customer_orders = json_decode(json_encode($customer_orders),true);
$total_product_count = 0;
foreach ( $customer_orders as $customer_order_data ) {
$Order_ID=$customer_order_data['ID'];
$Select_Order_Details = $wpdb->get_results( "SELECT COUNT(order_item_id) AS total_product_count FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_type='line_item' and order_id = $Order_ID");
$Select_Order_Details = json_decode(json_encode($Select_Order_Details),true);
foreach($Select_Order_Details as $Product_Count)
{
$total_product_count=$total_product_count+$Product_Count['total_product_count'];
}
}
echo ($total_product_count); exit;