如果客户购买了产品,如何获取特定产品的订单ID?我尝试了以下代码,但无效。感谢提前的帮助。
<?php
$order = new wc_get_order( $order_id );
$order->get_id();
echo $order->get_order_number();
?>
也尝试了此代码,但没有起作用。
$product_ids = array(37,53);
$order_ids = get_order_ids_from_bought_items( $product_ids );
以下功能使用非常轻巧的SQL查询,该查询将从给定客户的定义产品ID返回最后一个订单ID:
function get_last_order_id_from_product( $product_id, $user_id = 0 ) {
global $wpdb;
$customer_id = $user_id == 0 ? get_current_user_id() : $user_id;
return $wpdb->get_var( "
SELECT 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_type = 'shop_order'
AND pm.meta_key = '_customer_user'
AND pm.meta_value = $customer_id
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value = $product_id
ORDER BY p.ID DESC LIMIT 1
" );
}
代码在您的活动子主题(或活动主题)的功能上启用函数。测试并起作用。
如果客户尚未购买产品,则该功能将返回
false
。
用法示例:
在这里,您将设置产品ID 37
和可选的用户ID 153
(如果您不使用前面的代码结束函数可以获取当前用户ID)*/
$order_id = get_last_order_id_from_product( 37, 153 );
或当前用户:
$order_id = get_last_order_id_from_product( 37 );
function get_order_ids_from_bought_items() {
$prod_arr = array('37', '53');
$purchased = false;
$customer_orders = get_posts(array(
'numberposts' => -1,
'post_type' => 'shop_order',
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
));
foreach ($customer_orders as $order_post) {
$order = wc_get_order($order_post->ID);
foreach ($order->get_items() as $item) {
$product_id = $item->get_product_id();
if (in_array($product_id, $prod_arr))
$purchased = true;
}
}
return $purchased; // $order_post->ID for Order ID
}