我正在尝试列出属于某个产品类别的所有购买产品,例如“衣服”产品类别下的所有T恤订单。
我发现Woocommerce数据库结构非常混乱,您必须编写很长的查询才能获取简单的信息。
有人可以提供示例查询来获取某个类别的所有订单吗?
我知道这可能涉及wp_woocommerce_order_items
和wp_terms
表,但从那里迷路了。
答案 0 :(得分:1)
以下SQL查询将为您提供至少购买一次属于“衣服”产品类别category的产品ID的列表:
SELECT DISTINCT tr.object_id
FROM wp_term_relationships tr
INNER JOIN wp_term_taxonomy tt
ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN wp_terms t
ON tt.term_id = t.term_id
INNER JOIN wp_woocommerce_order_itemmeta oim
ON tr.object_id = oim.meta_value
INNER JOIN wp_woocommerce_order_items oi
ON oim.order_item_id = oi.order_item_id
INNER JOIN wp_posts as o
ON oi.order_id = o.ID
WHERE tt.taxonomy = 'product_cat'
AND t.slug = 'clothes'
AND oim.meta_key = '_product_id'
AND o.post_type = 'shop_order'
AND o.post_status IN ('wc-completed','wc-processing')
经测试可正常工作
或者在Wordpress中使用WPDB
类,可以使用:
global $wpdb;
$product_category = 'clothes'; // Term slug
$products_ids = $wpdb->get_col( "
SELECT DISTINCT tr.object_id
FROM wp_term_relationships tr
INNER JOIN wp_term_taxonomy tt
ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN wp_terms t
ON tt.term_id = t.term_id
INNER JOIN wp_woocommerce_order_itemmeta oim
ON tr.object_id = oim.meta_value
INNER JOIN wp_woocommerce_order_items oi
ON oim.order_item_id = oi.order_item_id
INNER JOIN wp_posts as o
ON oi.order_id = o.ID
WHERE tt.taxonomy = 'product_cat'
AND t.slug = '$product_category'
AND oim.meta_key = '_product_id'
AND o.post_type = 'shop_order'
AND o.post_status IN ('wc-completed','wc-processing')
");
// Pre-formatted raw display (an array of products ids)
echo '<pre>'; print_r($products_ids); echo '</pre>';