Allow Each Customer to Buy a Product Only Once
Stops logged-in customers from buying the same product twice, for example a course, a membership or a limited item, and tells them they already own it.
Opens WPIDE on
Code
$wpide_once_products = array(); // Product IDs limited to one purchase, empty for all.
add_filter( 'woocommerce_is_purchasable', function ( $purchasable, $product ) use ( $wpide_once_products ) {
if ( ! $purchasable || ! is_user_logged_in() ) {
return $purchasable;
}
$id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id();
if ( $wpide_once_products && ! in_array( $id, array_map( 'intval', $wpide_once_products ), true ) ) {
return $purchasable;
}
$user = wp_get_current_user();
return wc_customer_bought_product( $user->user_email, $user->ID, $id ) ? false : $purchasable;
}, 20, 2 );
add_action( 'woocommerce_single_product_summary', function () use ( $wpide_once_products ) {
global $product;
if ( ! is_user_logged_in() || ! $product instanceof WC_Product ) {
return;
}
if ( $wpide_once_products && ! in_array( $product->get_id(), array_map( 'intval', $wpide_once_products ), true ) ) {
return;
}
$user = wp_get_current_user();
if ( wc_customer_bought_product( $user->user_email, $user->ID, $product->get_id() ) ) {
echo '<p class="wpide-already-bought">' . esc_html( 'You have already purchased this product.' ) . '</p>';
}
}, 31 );
Notes
List product IDs in $product_ids to limit only those, or leave it empty for all products. Guests cannot be checked, so consider requiring an account.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.