小编典典

获取用户在Woocmmmerce中购买的商品总数

sql

我正在尝试找出一个函数,该函数可获取当前用户在所有下达的订单中购买的商品总数(不是总数,而是商品)。到目前为止,我已经发现了这一点(不起作用)-但是,此函数应该再次获得总计而不是项。一直在尝试对其进行编辑,但是到目前为止没有成功。

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

有任何想法吗?


阅读 183

收藏
2021-04-22

共1个答案

小编典典

已更新 (考虑了物料数量)

以下非常轻巧的功能将获得客户购买的商品总数:

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>'; ?>
2021-04-22