有很多方法可以做到这一点。在这里,我在一个自定义函数中使用了一个 SQL 查询和一个 $variation_id (要设置的变体 ID) 作为其中的参数:
function get_all_orders_items_from_a_product_variation( $variation_id ){
global $wpdb;
// Getting all Order Items with that variation ID
$item_ids_arr = $wpdb->get_col( $wpdb->prepare( "
SELECT `order_item_id`
FROM {$wpdb->prefix}woocommerce_order_itemmeta
WHERE meta_key LIKE '_variation_id'
AND meta_value = %s
", $variation_id ) );
return $item_ids_arr; // return the array of orders items ids
}
代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。
USAGE (此处以变体 ID 41 为例):
这将显示此变体 ID 的订单商品 ID 列表以及一些数据(例如)。
$items_ids = get_all_orders_items_from_a_product_variation( 41 );
// Iterating through each order item
foreach( $items_ids as $item_id ){
// Getting some data (the color value here)
$item_color = wc_get_order_item_meta( $item_id, 'pa_color', true );
// Displaying some data related to the current order item
echo 'Item ID: '. $item_id . ' with color "' . $item_color .'"<br>';
}
此代码已经过测试并且可以工作。
获取订单 ID (已更新)
现在,如果您需要获取所有订单 ID,您可以通过这种方式在该函数中使用另一个查询:
function get_all_orders_that_have_a_product_variation( $variation_id ){
global $wpdb;
// Getting all Order IDs with that variation ID
$order_ids_arr = $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT items.order_id
FROM {$wpdb->prefix}woocommerce_order_items AS items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS itemmeta ON items.order_item_id = itemmeta.order_item_id
WHERE meta_key LIKE '_variation_id'
AND meta_value = %s
", $variation_id ) );
return $order_ids_arr; // return the array of orders ids
}
代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。
USAGE (这里总是以变体 ID 41 为例):
这将显示此变体 ID 的订单 ID 列表及其状态(例如)。
$orders_ids = get_all_orders_that_have_a_product_variation( 41 );
// Iterating through each order item
foreach( $orders_ids as $order_id ){
// Getting an instance of the order object
$order = wc_get_order($order_id);
// Displaying some data related to the current order
echo 'Order #'. $order_id . ' has status "' . $order->get_status() .'"<br>';
}
此代码已经过测试并且可以工作。
您还可以通过这种方式将订单 ID 与其相关的商品 ID 组合成一个更复杂的数组:
function get_all_orders_and_item_ids_that_have_a_product_variation( $variation_id ){
global $wpdb;
// Getting all Order IDs and item ids with that variation ID
$results = $wpdb->get_results( $wpdb->prepare( "
SELECT items.order_id, items.order_item_id AS item_id
FROM {$wpdb->prefix}woocommerce_order_items AS items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS itemmeta ON items.order_item_id = itemmeta.order_item_id
WHERE meta_key LIKE '_variation_id'
AND meta_value = %s
", $variation_id ), ARRAY_A );
return $results; // return a multi-dimensional array of orders Ids / items Ids
}