购买产品后,将此产品订单ID添加到此用户元中。我可以使用此wc_customer_bought_product()
检查产品的购买状态。现在,我需要使用用户ID和产品ID获取此产品订单ID。我该如何实现?我的最终目标是在获得订单ID之后,我将通过此功能wp_delete_post()
$bronze = wc_customer_bought_product($current_user->user_email, $current_user->ID, 246014);
function get_customerorderid(){
global $post;
$order_id = $post->ID;
// Get an instance of the WC_Order object
$order = wc_get_order($order_id);
// Get the user ID from WC_Order methods
$user_id = $order->get_user_id(); // or $order->get_customer_id();
return $user_id;
}
get_customerorderid();
wp_delete_post(246014,true);
答案 0 :(得分:0)
您可以使用WPDB
类通过以下方式将自定义sql查询嵌入函数中:
function get_completed_orders_for_user_from_product_id( $product_id, $user_id = 0 ) {
global $wpdb;
$order_status = 'wc-completed';
// If optional $user_id argument is not set, we use the current user ID
$customer_id = $user_id === 0 ? get_current_user_id() : $user_id;
// Return customer orders IDs containing the defined product ID
return $wpdb->get_col( $wpdb->prepare("
SELECT DISTINCT woi.order_id
FROM {$wpdb->prefix}posts p
INNER JOIN {$wpdb->prefix}postmeta pm
ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items woi
ON p.ID = woi.order_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta woim
ON woi.order_item_id = woi.order_item_id
WHERE p.post_status = '%s'
AND pm.meta_key = '_customer_user'
AND pm.meta_value = '%d'
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value LIKE '%d'
ORDER BY woi.order_item_id DESC
", $order_status, $customer_id, $product_id ) );
}
代码进入您的活动子主题(或活动主题)的functions.php文件中。。经过测试,可以正常工作。
用法与wp_delete_post()
一起删除包含特定产品(id: 246014
)的相关订单:< / p>
// Get all orders containing 246014 product ID for the current user
$orders_ids = get_completed_orders_for_user_from_product_id( 246014 );
// Checking that, the orders IDs array is not empty
if( count($orders_ids) > 0 ) {
// Loop through orders IDs
foreach ( $orders_ids as $order_id ) {
// Delete order post data
wp_delete_post( $order_id, true );
}
// Add the order(s) ID(s) in user meta (example)
update_user_meta( get_current_user_id(), 'item_246014', implode( ',', $orders_ids ) );
}
相关线程: