首页 > 解决方案 > 在 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);

标签: phpsqlwordpresswoocommerceorders

解决方案


您可以使用WPDBClass 将自定义 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 ) );
}

相关话题:


推荐阅读