获取用户在 Woocmmmerce 中购买的商品总数 [英] Get user total purchased items count in Woocmmmerce

查看:66
本文介绍了获取用户在 Woocmmmerce 中购买的商品总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一个函数,该函数可以将当前用户购买的商品总数(不是总金额,而是商品)作为所有已下订单.到目前为止,我已经发现了这个(这不起作用) - 但是这个函数应该再次获得总和而不是项目.一直在尝试编辑它以使其正常工作,但到目前为止没有成功.

I'm trying to figure out a function which get current user total number of purchased items (not total sum but items) across as all placed orders. So far I have found this (which doesn't work) - but again this function should get total sum and not items. Been trying to edit it to work but no success so far.

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;
}

有什么想法吗?

推荐答案

更新 (考虑物品数量)

以下非常轻量级的函数将获取客户购买的商品总数:

The following very lightweight function will get the total purchased items count by a customer:

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 文件中.经测试有效.

Code goes in function.php file of your active child theme (or active theme). Tested and works.

用法示例

1) 显示当前用户购买的商品总数:

1) Display the current user total purchased items count:

<?php echo '<p>Total purchased items: ' . get_user_total_purchased_items() . '</p>'; ?>

2) 显示给定用户 ID 的购买商品总数:

2) Display the total purchased items count for a given user ID:

// Here the user ID is 105
<?php echo '<p>Total purchased items: ' . get_user_total_purchased_items(105) . '</p>'; ?>

这篇关于获取用户在 Woocmmmerce 中购买的商品总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆