获取用户在Woocommerce中购买最多的产品

时间:2019-03-19 11:14:05

标签: php sql wordpress woocommerce product

在Woocommerce中,我试图为客户从订单详细信息中购买最多的产品。因此,我想获得用户购买频率更高的产品ID。

我还没有找到办法。 Woocommerce有可能吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

以下非常简单的SQL查询将为您提供当前客户购买的10个最常见产品ID的数组:

// 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
" );

将提供一系列产品ID…经过测试并可以正常工作。