How to use wc_customer_bought_product function to check if customer bought product in an array

允我心安 提交于 2019-12-02 10:35:06
function check_is_category_A_customer(array $product_ids)
{
$product_ids= array ('2258','2253','2242');//for testing
global $woocommerce;
$user_id = get_current_user_id();
$current_user= wp_get_current_user();
$customer_email = $current_user->email;


foreach($product_ids as $item):
    if ( wc_customer_bought_product( $customer_email, $user_id, $item) )
       return true;
    endforeach; 

return false;
}

You were not setting the $current_user object, see above for the correction.

So David helped me get on the right track and I should have known how to pass 1 product id at a time inside the same function but I didn't.

After some research and study, I wrote a new function using else if statements for each product id, tested it, and so far it is working.

So, even if using an array or a category id would have been more practical (but I don't know how to do it, yet) I am sharing this solution for other people who might wanna achieve the same goal :

// Create function to check if client bought a product from array A
function check_is_category_A_customer()
{
global $woocommerce;
$user_id = get_current_user_id();
$current_user= wp_get_current_user();
$customer_email = $current_user->email;

if ( wc_customer_bought_product( $customer_email, $user_id,'2258')) {
return true;
} else if ( wc_customer_bought_product( $customer_email, $user_id,'2253')) {
return true;
} else if ( wc_customer_bought_product( $customer_email, $user_id,'2242')) {
return true;
}
return false;
}
// Create shortcode to display menu for customers cat A
add_shortcode('CATA','check_cat_bought_A');
function check_cat_bought_A($atts,$content=""){
if( check_is_category_A_customer() ){
return do_shortcode($content);
}
}

Thanks again to David for pointing the direction :) Of course if someone has a better solution, or sees any mistakes in this, please speak up.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!