【发布时间】:2019-10-14 23:26:58
【问题描述】:
我在另一个页面上找到了此代码。
function jdr_get_orders_ids_from_product_id( $product_id, $orders_statuses = [ 'wc-completed' ] ) {
global $wpdb;
// Define HERE the orders status to include in <== <== <== <== <== <== <==
$orders_statuses = "'" . implode( "', '", $orders_statuses ) . "'";
# Get All defined statuses Orders IDs for a defined product ID (or variation ID)
return $wpdb->get_col( "
SELECT DISTINCT woi.order_id
FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p
WHERE woi.order_item_id = woim.order_item_id
AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses )
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value LIKE '$product_id'
ORDER BY woi.order_item_id DESC"
);
}
使用它,我可以找到任何不包含特定 $product_id 的订单的 $order_ids。
但是,我想更进一步,获取订单中每种特定产品的数量。
我们可以使用如下几个自定义函数来做到这一点:
function jdr_qty_sold_by_product_id( $product_id ) {
$qty = 0;
foreach( jdr_get_orders_ids_from_product_id( $product_id ) as $order_id )
$qty = $qty + jdr_get_order_item_qty( $order_id, $product_id );
return $qty;
}
function jdr_get_order_item_qty( $order_id, $product_id ) {
$_order = wc_get_order( $order_id );
foreach ($_order->get_items() as $item_id => $item_data) {
$product = $item_data->get_product();
if ( $product->get_id() == $product_id )
return $item_data->get_quantity();
}
return 0;
}
但这需要循环遍历每个订单和每个项目,这需要很长时间才能加载到需要此功能的页面(100 多个订单)。
请问有没有类似第一个函数的SQL方案?
任何帮助表示赞赏。
【问题讨论】:
标签: wordpress woocommerce