Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.