[英]Get the orders IDs related to a product bought by a customer in Woocommerce
I have the products ids as an array and I would like to get the list of order ids if the customer has purchased that product. 我将产品ID作为一个数组,如果客户购买了该产品,我想获得订单ID列表。
I have the customer purchased product ids with me. 我和客户一起购买了产品ID。 Somehow, I have to get the linked order id and cancel that order if customer purchases new product.
不知何故,如果客户购买新产品,我必须获得链接订单ID并取消该订单。
To check if a customer has purchased a product I am using the function has_bought_items()
from this answer thread: Check if a customer has purchased a specific products in WooCommerce 要检查客户是否购买了产品,我将使用此答案主题中的函数
has_bought_items()
: 检查客户是否在WooCommerce中购买了特定产品
May be it can be tweaked to get the desired output? 可能是可以调整以获得所需的输出?
The following custom function made with a very light unique SQL query, will get all the Orders IDs from an array of products IDs (or a unique product ID) for a given customer. 使用非常轻的唯一SQL查询创建的以下自定义函数将从给定客户的产品ID(或唯一产品ID)数组中获取所有订单ID。
Based on code from: Check if a customer has purchased a specific products in WooCommerce
基于以下代码: 检查客户是否在WooCommerce中购买了特定产品
function get_order_ids_from_bought_items( $product_ids = 0, $customer_id = 0 ) {
global $wpdb;
$customer_id = $customer_id == 0 || $customer_id == '' ? get_current_user_id() : $customer_id;
$statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
if ( is_array( $product_ids ) )
$product_ids = implode(',', $product_ids);
if ( $product_ids != ( 0 || '' ) )
$meta_query_line = "AND woim.meta_value IN ($product_ids)";
else
$meta_query_line = "AND woim.meta_value != 0";
// Get Orders IDs
$results = $wpdb->get_col( "
SELECT DISTINCT p.ID FROM {$wpdb->prefix}posts AS p
INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $statuses ) . "' )
AND pm.meta_key = '_customer_user'
AND pm.meta_value = $customer_id
AND woim.meta_key IN ( '_product_id', '_variation_id' )
$meta_query_line
" );
// Return an array of Order IDs or an empty array
return sizeof($results) > 0 ? $results : array();
}
Code goes in function.php file of your active child theme (or active theme). 代码位于活动子主题(或活动主题)的function.php文件中。 Tested and works.
经过测试和工作。
1) For the current logged in customer (and 2 product Ids in an array): 1)对于当前登录的客户(以及阵列中的2个产品ID):
$product_ids = array(37,53);
$order_ids = get_order_ids_from_bought_items( $product_ids );
2) For a defined User ID and one product ID: 2)对于定义的用户ID和一个产品ID:
$product_id = 53;
$user_id = 72;
$order_ids = get_order_ids_from_bought_items( $product_id, $user_id );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.