我已经问过这个问题here并得到了部分有效的答案。但要回顾我之前的问题。我在查询后查询woocommerce产品,然后将它们显示在排行榜的列表中。我还需要显示每种产品的个人零售额。当我说零售额时,我并不是指销售数量,我的意思是销售的总金额。我现在有了工作代码来获得整个商店的零售总额,这非常棒。
// All-time Sales for entire store
$query = array();
$query['fields'] = "SELECT SUM( postmeta.meta_value ) FROM {$wpdb->posts} as posts";
$query['join'] = "INNER JOIN {$wpdb->postmeta} AS postmeta ON posts.ID = postmeta.post_id ";
$query['where'] = "WHERE posts.post_type IN ( '" . implode( "','", wc_get_order_types( 'reports' ) ) . "' ) ";
$query['where'] .= "AND posts.post_status IN ( 'wc-" . implode( "','wc-", apply_filters( 'woocommerce_reports_order_statuses', array( 'completed', 'processing', 'on-hold' ) ) ) . "' ) ";
$query['where'] .= "AND postmeta.meta_key = '_order_total' ";
$sales = $wpdb->get_var( implode( ' ', $query ) );
现在的问题是,我似乎无法让这个用于个别产品。目前我有这段代码:
$product_id = 10;
$query = array();
$query['fields'] = "SELECT SUM( postmeta.meta_value ) FROM {$wpdb->posts} as posts";
$query['join'] = "INNER JOIN {$wpdb->postmeta} AS postmeta ON posts.ID = postmeta.post_id ";
$query['where'] = sprintf( "WHERE posts.ID = %n", $product_id );
$query['where'] .= "AND posts.post_status IN ( 'wc-" . implode( "','wc-", apply_filters( 'woocommerce_reports_order_statuses', array( 'completed', 'processing', 'on-hold' ) ) ) . "' ) ";
$query['where'] .= "AND postmeta.meta_key = '_order_total' ";
$sales = $wpdb->get_var( implode( ' ', $query ) );
但不幸的是,它只显示0。是否有人可以帮助A.修复单个产品的代码,或B.找到更好的方法在产品到产品的基础上执行此操作?
感谢您对此主题的任何帮助。
答案 0 :(得分:0)
我想知道如何做到这一点,这就是我想出来的。
SELECT SUM( order_item_meta__line_total.meta_value) as order_item_amount FROM wp_posts AS posts INNER JOIN wp_woocommerce_order_items AS order_items ON posts.ID = order_items.order_id INNER JOIN wp_woocommerce_order_itemmeta AS order_item_meta__line_total ON (order_items.order_item_id = order_item_meta__line_total.order_item_id) AND (order_item_meta__line_total.meta_key = '_line_total') INNER JOIN wp_woocommerce_order_itemmeta AS order_item_meta__product_id_array ON order_items.order_item_id = order_item_meta__product_id_array.order_item_id WHERE posts.post_type IN ( 'shop_order','shop_order_refund' ) AND posts.post_status IN ( 'wc-completed','wc-processing','wc-on-hold') AND ( ( order_item_meta__product_id_array.meta_key IN ('_product_id','_variation_id') AND order_item_meta__product_id_array.meta_value IN ('".$product_id."') ))
您可能需要将此查询构造为上面的数组。