Ansarul Haque
Ansarul Haque

Reputation: 51

WooCommerce Avoid add to cart for non logged user

In my WooCommerce shop, when a customers is not logged in I would like to avoid him adding to cart asking him to either login or register an account…

Is it possible?

Upvotes: 1

Views: 7172

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Updated - You could use this 2 little snippets of code, that will:

  • Replace add-to-cart button/link in shop pages and archives pages (for non logged in users).
  • Avoid non logged in customers adding to cart and displaying a custom message.

Here is the code:

// Replacing add-to-cart button in shop pages and archives pages (forn non logged in users)
add_filter( 'woocommerce_loop_add_to_cart_link', 'conditionally_change_loop_add_to_cart_link', 10, 2 );
function conditionally_change_loop_add_to_cart_link( $html, $product ) {
    if ( ! is_user_logged_in() ) {
        $link = get_permalink($product_id);
        $button_text = __( "View product", "woocommerce" );
        $html = '<a href="'.$link.'" class="button alt add_to_cart_button">'.$button_text.'</a>';
    }
    return $html;
}

// Avoid add to cart for non logged user (or not registered)
add_filter( 'woocommerce_add_to_cart_validation', 'logged_in_customers_validation', 10, 3 );
function logged_in_customers_validation( $passed, $product_id, $quantity) {
    if( ! is_user_logged_in() ) {
        $passed = false;

        // Displaying a custom message
        $message = __("You need to be logged in to be able adding to cart…", "woocommerce");
        $button_link = get_permalink( get_option('woocommerce_myaccount_page_id') );
        $button_text = __("Login or register", "woocommerce");
        $message .= ' <a href="'.$button_link.'" class="login-register button" style="float:right;">'.$button_text.'</a>';

        wc_add_notice( $message, 'error' );
    }
    return $passed;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested ad works.

Upvotes: 6

Related Questions