45
We already saw how to hide add to cart for logged out users and how to find out if a user has already bought a given product – so I said why not combine the two snippets and figure out how to hide the add to cart button if a logged in customer has already purchased a product?
After that, however, I realized that the “woocommerce_is_purchasable” filter offered by the WooCommerce plugin makes the task much easier than just combining the two mini-plugins above.
So, here’s how it’s done – enjoy!
PHP Snippet: Deny Further Sales If User Has Already Purchased a Product @ Shop / Single Product Page
This snippet will:
- Hide the Add to Cart completely on the single product page
- Rename the Add to Cart on the Shop Page to “Read More”
- Make it impossible to add the item to cart even with an URL – it will show a red “Sorry, this product cannot be purchased.” error in such case
/**
* @snippet Hide Add Cart If Already Purchased - WooCommerce
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WooCommerce 5
* @donate $9 https://tutoraspire.com
*/
add_filter( 'woocommerce_is_purchasable', 'tutoraspire_hide_add_cart_if_already_purchased', 9999, 2 );
function tutoraspire_hide_add_cart_if_already_purchased( $is_purchasable, $product ) {
if ( wc_customer_bought_product( '', get_current_user_id(), $product->get_id() ) ) {
$is_purchasable = false;
}
return $is_purchasable;
}