Menu Close

Force Visitor to Log in or Create an Account before proceeding to Cart Woocommerce

Force Visitor to Log in or Create an Account before proceeding to Cart Woocommerce

//Force Visitor to Log in or Create an Account before proceeding to Cart Woocommerce

//Add to Functions.php in Child Theme

<?php
add_action( ‘wp_enqueue_scripts’, ‘homesbyprivatesale_child_enqueue_styles’ );
function homesbyprivatesale_child_enqueue_styles() {
wp_enqueue_style( ‘parent-style’, get_template_directory_uri() . ‘/style.css’ );
}
// 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 quantity_inputs_for_woocommerce_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 add the product to the 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;
}