1
votes

In Woocommerce, I am trying to get for a customer, the most purchased products from order details. So I would like to get the Product IDs which are more frequently purchased by user.

I haven't find the way yet. Is that possible in Woocommerce?

Any help is appreciated.

1
You want to popular product or most purchased product ?Dhruv
No i want to often product list in user dashboard @DhruvNikunj Kathrotiya

1 Answers

1
votes

The following very light SQL query will give you an array of the 10 most purchased product IDs by the current customer:

// Get the current user ID
$user_id = get_current_user_id(); // (or set a user ID dynamically)

// Number of product Ids Max
$limit = 10; // 0 or -1 for unlimited

global $wpdb;

$limit_clause = $limit > 0 ? "LIMIT $limit" : "";

$products_ids = $wpdb->get_col( "
    SELECT DISTINCT products.ID
    FROM {$wpdb->prefix}posts as products
    JOIN {$wpdb->prefix}postmeta as product_meta
        ON products.ID = product_meta.post_id
    JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_itemmeta
        ON products.ID = order_itemmeta.meta_value
    JOIN {$wpdb->prefix}woocommerce_order_items as order_items
        ON order_itemmeta.order_item_id = order_items.order_item_id
    JOIN {$wpdb->prefix}posts as orders
        ON order_items.order_id = orders.ID
    JOIN {$wpdb->prefix}postmeta as order_meta
        ON orders.ID = order_meta.post_id
    WHERE orders.post_type = 'shop_order'
    AND orders.post_status IN ('wc-completed','wc-processing')
    AND order_meta.meta_key = '_customer_user'
    AND order_meta.meta_value = '$user_id'
    AND order_itemmeta.meta_key = '_product_id'
    AND products.post_type = 'product'
    AND products.post_status = 'publish'
    AND product_meta.meta_key = 'total_sales'
    ORDER BY cast(product_meta.meta_value as unsigned) DESC  $limit_clause
" );

Will give an array of product IDs… Tested and works.