Reputation: 31
I want only allow one purchase for each product, so I want to disable the add to cart for the user who already purchased that product. I've been reading and I think I should use the woocommerce_is_purchasable hook but I have no idea how to do it, I would appreciate the help, thank you.
Upvotes: 1
Views: 193
Reputation: 21
Assuming you're talking about simple products*, you can do this by hooking into is_purchasable
.
For the logged in customer, the following code gets the product ID's of all past orders. If the current product ID is in that collection, it returns false for is_purchasable
.
Add it to the functions.php
file of your child theme.
add_filter('woocommerce_is_purchasable', 'preventPurchaseIfAlreadyOrdered', 10, 2);
function preventPurchaseIfAlreadyOrdered($is_purchasable, $product) {
$productId = $product->get_id();
$orderedItemIdArray = getOrdersItemIdsForCurrentUser();
$is_purchasable = !in_array($productId, $orderedItemIdArray);
return $is_purchasable;
}
function getOrdersItemIdsForCurrentUser() {
$orders = wc_get_orders(['author' => get_current_user_id()]);
if (empty($orders)) return;
$orderedItemIdArray = [];
foreach ($orders as $order) {
$items = $order->get_items();
foreach ($items as $item) {
$orderedItemIdArray[] = $item->get_product_id();
}
}
return $orderedItemIdArray;
}
The code has been tested and works.
* for variable products, the selected variation can change without reloading the page, i.e. via Ajax. That process is more involved (but also possible).
Upvotes: 1