There are many ways to achieve this. Here I use a user-defined function with one SQL query and (change identifier for installation) as a parameter in it: $variation_id
function get_all_orders_items_from_a_product_variation( $variation_id ){
global $wpdb;
$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;
}
The code goes in the function.php file of your active child theme (or theme), as well as in any plug-in file.
USAGE (here, for example, with option ID 41):
This will display a list of order item identifiers for this variant identifier with some data (for example).
$items_ids = get_all_orders_items_from_a_product_variation( 41 );
foreach( $items_ids as $item_id ){
$item_color = wc_get_order_item_meta( $item_id, 'pa_color', true );
echo 'Item ID: '. $item_id . ' with color "' . $item_color .'"<br>';
}
This code has been verified and works.
()
, , :
function get_all_orders_that_have_a_product_variation( $variation_id ){
global $wpdb;
$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 $orders_ids;
}
function.php ( ), .
( ID 41):
().
$orders_ids = get_all_orders_that_have_a_product_variation( 41 );
foreach( $orders_ids as $order_id ){
$order = wc_get_order($order_id);
echo 'Order #'. $order_id . ' has status "' . $order->get_status() .'"<br>';
}
.
:
function get_all_orders_and_item_ids_that_have_a_product_variation( $variation_id ){
global $wpdb;
$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;
}