php - 在 WooCommerce 中购买产品后,将相关订单 ID 添加为用户元数据
问题描述
购买产品后,在此用户元中添加此产品订单 ID。我可以使用这个检查产品购买状态wc_customer_bought_product()
。现在我需要使用 UserID 和产品 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);
解决方案
您可以使用WPDB
Class 将自定义 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 文件中。测试和工作。
USAGE withwp_delete_post()
删除包含特定产品(id: 246014
)的相关订单:
// 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 ) );
}
相关话题:
推荐阅读
- python - 把弦变成时间
- cloudcaptain - 不加密 AMI 的 Boxfuse 部署
- javascript - 如何使用 c:forEach 标签初始化数组(在 Javascript 中)?
- vba - 将多个范围添加到打印区域
- android - 此处不允许使用元素形状
- ssl - 为什么不在 TLS 中使用 ECDSA 和 PSK?
- javascript - 在 ios 中设置 TextInput 占位符垂直居中 - React Native
- excel - 使用 Excel 中的单元格格式将 AM 更改为 PM 将 12 小时添加到特定单元格中的任何时间
- c# - 将 pdf 渲染解耦为可重用的程序集/使用不同的渲染策略
- python - 如何在 Tensorflow 中初始化 LSTMStateTuple?