简体   繁体   中英

Get the orders IDs related to a product bought by a customer in Woocommerce

I have the products ids as an array and I would like to get the list of order ids if the customer has purchased that product.

I have the customer purchased product ids with me. Somehow, I have to get the linked order id and cancel that order if customer purchases new product.

To check if a customer has purchased a product I am using the function has_bought_items() from this answer thread: Check if a customer has purchased a specific products in WooCommerce

May be it can be tweaked to get the desired output?

The following custom function made with a very light unique SQL query, will get all the Orders IDs from an array of products IDs (or a unique product ID) for a given customer.

Based on code from: 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();
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


USAGE Examples:

1) For the current logged in customer (and 2 product Ids in an array):

$product_ids = array(37,53);
$order_ids = get_order_ids_from_bought_items( $product_ids );

2) For a defined User ID and one product ID:

$product_id = 53;
$user_id    = 72;
$order_ids  = get_order_ids_from_bought_items( $product_id, $user_id );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM