有很多方法可以做到这一点。在这里,我在自定义函数中使用一个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 $orders_ids; // 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
}
非常感谢您的详细解答!我最终使用了第二个函数和WC函数的组合来充实数据,但会调查我是否可以进行优化,但从查询中获得全部。 – Simon
不适用于我,可能是版本问题?仅获得空白数组。 –
我试图添加获取订单ID,使用第二个功能与自定义前缀只,但没有运气。它只是显示空白数组。即使试图检查功能,然后发现'item_ids_arr'显示空白数组。 –