wc_customer_bought_product

Checks if a user (by email or ID or both) has bought an item.

Description

wc_customer_bought_product( (string) $customer_email, (int) $user_id, (int) $product_id ); 

Parameters (3)

0. $customer_email (string)
The customer email.
1. $user_id (int)
The user id.
2. $product_id (int)
The product id.

Usage

  1. if ( !function_exists( 'wc_customer_bought_product' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-user-functions.php'; 
  3.  
  4. // The customer email. 
  5. $customer_email = ''; 
  6.  
  7. // The user id. 
  8. $user_id = -1; 
  9.  
  10. // The product id. 
  11. $product_id = -1; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = wc_customer_bought_product($customer_email, $user_id, $product_id); 
  15.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-user-functions.php  
  1. function wc_customer_bought_product( $customer_email, $user_id, $product_id ) { 
  2. global $wpdb; 
  3.  
  4. $transient_name = 'wc_cbp_' . md5( $customer_email . $user_id . WC_Cache_Helper::get_transient_version( 'orders' ) ); 
  5.  
  6. if ( false === ( $result = get_transient( $transient_name ) ) ) { 
  7. $customer_data = array( $user_id ); 
  8.  
  9. if ( $user_id ) { 
  10. $user = get_user_by( 'id', $user_id ); 
  11.  
  12. if ( isset( $user->user_email ) ) { 
  13. $customer_data[] = $user->user_email; 
  14.  
  15. if ( is_email( $customer_email ) ) { 
  16. $customer_data[] = $customer_email; 
  17.  
  18. $customer_data = array_map( 'esc_sql', array_filter( array_unique( $customer_data ) ) ); 
  19. $statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() ); 
  20.  
  21. if ( sizeof( $customer_data ) == 0 ) { 
  22. return false; 
  23.  
  24. $result = $wpdb->get_col( " 
  25. SELECT im.meta_value FROM {$wpdb->posts} AS p 
  26. INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id 
  27. INNER JOIN {$wpdb->prefix}woocommerce_order_items AS i ON p.ID = i.order_id 
  28. INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS im ON i.order_item_id = im.order_item_id 
  29. WHERE p.post_status IN ( 'wc-" . implode( "', 'wc-", $statuses ) . "' ) 
  30. AND pm.meta_key IN ( '_billing_email', '_customer_user' ) 
  31. AND im.meta_key IN ( '_product_id', '_variation_id' ) 
  32. AND im.meta_value != 0 
  33. AND pm.meta_value IN ( '" . implode( "', '", $customer_data ) . "' ) 
  34. " ); 
  35. $result = array_map( 'absint', $result ); 
  36.  
  37. set_transient( $transient_name, $result, DAY_IN_SECONDS * 30 ); 
  38. return in_array( absint( $product_id ), $result );