Avoid customers purchasing the same product again if checked as a guest in WooCommerce

Avoid customers purchasing the same product again if checked as a guest in WooCommerce on child sites.

Snippet Type

Execute on Child Sites

Snippet

function action_woocommerce_check_cart_items() {
    // Retrieve the current user object
    $current_user = wp_get_current_user();
    
    // Initialize
    $flag = false;
    
    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // Check for variantions
        $product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
        
        // Checks if a user (by email or ID or both) has bought an item
        if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) {
            // Flag becomes true
            $flag = true;
            
            // Break loop
            break;
        }
    }
    
    // True
    if ( $flag ) {
        // Clear all other notices          
        wc_clear_notices();

        // Avoid checkout display an error notice
        wc_add_notice( __( 'My custom error message', 'woocommerce' ), 'error' );
        
        // Optional: remove proceed to checkout button
        remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );   
    }
}   
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.