简体   繁体   中英

Single specific Product purchase for logged in users in Woocommerce

Is it possible that registered users on my Woocommerce store could only buy one time a specific product?

Also if they try to re-purchase that specific product, a warning message would prompt and they will not be able to check it out…

It can be done with this two hooked functions (only for logged in users) .

1) The first one will check that:

  • the specific product is not already in cart (avoiding add to cart)
  • the customer has not already purchased this product before (avoiding add to cart)

2) The second one, will remove the quantity field for this specific product, allowing only one product to be added to cart.

The code (you will have to set your specific product ID in both functions) :

// Check on add to cart action and display a custom notice
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 3 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity ) {
    if ( ! is_user_logged_in() ) return $passed; // Only logged in users

    // HERE define your targeted Product ID
    $targeted_product_id = 37;

    // Check if customer has already bought the targeted Product ID
    if( wc_customer_bought_product( '', get_current_user_id(), $targeted_product_id ) ){
        //$passed = false;
        //$notice = __('You have already bought this product once', 'woocommerce');
    }

    // Check if product is in cart items
    if ( ! WC()->cart->is_empty() )
        foreach( WC()->cart->get_cart() as $cart_item )
            if( $cart_item['product_id'] == $targeted_product_id && $product_id == $targeted_product_id ){
                $passed = false;
                $notice = __('This product is already in cart', 'woocommerce');
                break;
            }

    // Displaying a custom error notice
    if( ! $passed )
        wc_add_notice( $notice, 'error' );

    return $passed;
}

// Removing the quantity field (allowing only one product quantity)
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 10, 2 );
function custom_quantity_input_args( $args, $product ) {
    if ( ! is_user_logged_in() ) return $args; // Only logged in users

    // HERE define your targeted Product ID
    $targeted_product_id = 37;

    if( $product->get_id() != $targeted_product_id ) return $args;

    $args['input_value'] = 1; // Start from this value (default = 1)
    $args['min_value']   = 1; // Min value (default = 0)
    $args['max_value']   = 1; // Min value (default = 0)

    return $args;
}

Code goes in function.php file of the active child theme (or active theme).

Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM