Skip to content

Instantly share code, notes, and snippets.

@stevenhoney
Created October 13, 2016 13:06
Show Gist options
  • Save stevenhoney/d6e6ef3ed1002ad71fc4693c377f4346 to your computer and use it in GitHub Desktop.
Save stevenhoney/d6e6ef3ed1002ad71fc4693c377f4346 to your computer and use it in GitHub Desktop.
<?php
function olivier_customer_bought_product( $customer_email, $user_id, $product_id ) {
global $wpdb;
$transient_name = 'wc_cbp_' . md5( $customer_email . $user_id . WC_Cache_Helper::get_transient_version( 'orders' ) );
if ( false === ( $result = get_transient( $transient_name ) ) ) {
$customer_data = array( $user_id );
if ( $user_id ) {
$user = get_user_by( 'id', $user_id );
if ( isset( $user->user_email ) ) {
$customer_data[] = $user->user_email;
}
}
if ( is_email( $customer_email ) ) {
$customer_data[] = $customer_email;
}
$customer_data = array_map( 'esc_sql', array_filter( array_unique( $customer_data ) ) );
if ( sizeof( $customer_data ) == 0 ) {
return false;
}
$result = $wpdb->get_col( "
SELECT im.meta_value FROM {$wpdb->posts} AS p
INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items AS i ON p.ID = i.order_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS im ON i.order_item_id = im.order_item_id
WHERE p.post_status IN ( 'wc-completed', 'wc-processing', 'mobile-access' )
AND pm.meta_key IN ( '_billing_email', '_customer_user' )
AND im.meta_key IN ( '_product_id', '_variation_id' )
AND im.meta_value != 0
AND pm.meta_value IN ( '" . implode( "','", $customer_data ) . "' )
" );
$result = array_map( 'absint', $result );
set_transient( $transient_name, $result, DAY_IN_SECONDS * 30 );
}
return in_array( absint( $product_id ), $result );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment