Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active February 23, 2023 01:20
Show Gist options
  • Save sabrina-zeidan/2bfbae98a1e13cf95f7c00c32fe4c5b1 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/2bfbae98a1e13cf95f7c00c32fe4c5b1 to your computer and use it in GitHub Desktop.
Disable repeat purchase WooCommerce [WordPress]
/** Disable repeat purchase V 22.20 7:40 -- on Adding to Cart check **/
add_filter( 'woocommerce_add_to_cart_validation', 'limit_cart_items_from_category', 10, 5 );
function limit_cart_items_from_category ( $passed, $product_id, $quantity, $variation_id = 0, $variations = null ){
$current_product_id = ($variation_id === 0) ? $product_id : $variation_id;
// Loop through cart items checking if the product is already in cart
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $cart_item['data']->get_id() == $current_product_id ) {
wc_add_notice( __('This product is already in your cart.', 'woocommerce' ), 'error' );
return false;
}
}
//If it's not in the cart --> check if it's available in their Downloads
$user_id = get_current_user_id();
//$user_id = 2347;
// $time_start = microtime(true);
$their_downloads = wc_get_customer_available_downloads( $user_id );
// $time_end = microtime(true);
// $execution_time = ($time_end - $time_start);
$ids = array_map(function($item) {
return $item['product_id'];
}, $their_downloads);
if (in_array($current_product_id, $ids)){
wc_add_notice( __('You have bought this product before, download it from <a href="'.get_site_url().'/my-account/my-library/">your Library.</a>', 'woocommerce' ), 'error' );
return false;
}
return $passed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment