Find user orders that have a specific product in WooCommerce

Have you ever needed to find the order IDs for a particular product for a given customer in WooCommerce? It’s not a straightforward task, but fortunately, there is a simple function that can help.

The bytflow_get_order_ids_for_product() function makes it easy to get the order IDs for a particular product for a given customer. Here is the function:

function bytflow_get_order_ids_for_product( $product_id, $customer_id ) {
  // Initialize an empty array to store the order IDs
  $order_ids = array();
  
  // Get all orders for the customer
  $customer_orders = wc_get_orders( array(
    'customer_id' => $customer_id,
  ) );
  
  // Loop through each order
  foreach ( $customer_orders as $customer_order ) {
    // Get the items in the order
    $order_items = $customer_order->get_items();
    
    // Loop through each item in the order
    foreach ( $order_items as $item ) {
      // Check if the item is the product we're looking for
      if ( $item['product_id'] == $product_id ) {
        // If it is, add the order ID to the array
        $order_ids[] = $customer_order->get_id();
      }
    }
  }
  
  // Return the array of order IDs
  return $order_ids;
}

This function takes two arguments:

  • $product_id: The ID of the product for which you want to get the order IDs.
  • $customer_id: The ID of the customer for which you want to get the orders.

It returns an array of order IDs for the orders that contain the given product for the given customer.

You can use this function like this:

$product_id = 123;
$customer_id = 456;
$order_ids = bytflow_get_order_ids_for_product( $product_id, $customer_id );

This will get the order IDs for the product with ID 123 for the customer with ID 456. The $order_ids variable will be an array of order IDs for the orders that contain the product.

Leave a Comment