我将商品ID当作一个数组,如果客户购买了该商品,我想获得订单ID列表。
我有客户与我一起购买产品ID。不知何故,如果客户购买新产品,我必须获得链接的订单ID并取消该订单。
要检查客户是否购买了产品,我正在通过以下答案线程使用功能has_bought_items()
:Check if a customer has purchased a specific products in WooCommerce
是否可以对其进行调整以获得所需的输出?
答案 0 :(得分:2)
以下通过非常简单的独特SQL查询创建的自定义函数将从给定客户的产品ID数组(或唯一产品ID)中获取所有订单ID。
基于来自Check if a customer has purchased a specific products in 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();
}
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。
1)对于当前已登录的客户(以及阵列中的2个产品ID):
$product_ids = array(37,53);
$order_ids = get_order_ids_from_bought_items( $product_ids );
2)对于已定义的用户ID和一个产品ID:
$product_id = 53;
$user_id = 72;
$order_ids = get_order_ids_from_bought_items( $product_id, $user_id );