Search code examples
phpsqlwordpresswoocommerceorders

Get user total purchased items count in 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;
}

Any ideas?


Solution

  • Updated (Taking in account the item quantity)

    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'
        " );
    }
    

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


    USAGE Example

    1) Display the current user total purchased items count:

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

    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>'; ?>