I wondered if anyone can help me?
I am using a WordPress site with Woocommerce plugin.
I am using a piece of code to avoid adding to cart for non logged in customers which I found on this site, it works great apart from one issue. It doesn’t work on the product page. When you click the add to cart button, it doesn’t redirect to the custom login page like it does if you press the button on the category view page. Instead the page just refreshes.
I put the code in to the functions.php file. I’ve then tried putting it into a few other places but that hasn’t worked. Could anyone help me with this and let me know if there is another location I should be putting the code in? Thanks in advance, I’d really appreciate the help!
Here’s the link to the question and the code is below: WooCommerce Avoid add to cart for non logged user
// 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 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;
}
2
Answers
yes, you can do it by just adding following code into your active theme function.php file.
Firstly, your function hook for
woocommerce_loop_add_to_cart_link
is incorrect. You are usingconditionally_change_loop_add_to_cart_link
rather thanquantity_inputs_for_woocommerce_loop_add_to_cart_link
.Secondly, your URL for the link is using the current product page ID, which is going to point you at the current product page URL and not another page.
Other than that, you had it mostly correct with
woocommerce_add_to_cart_validation
.EDIT:
For product single pages, if you look at
content-single-product.php
in Woocommerce, the actionwoocommerce_template_single_add_to_cart
seems to handle what the “add to cart” form looks like. If you’d like to not show the add to cart form, you’ll want to first remove the action from thewoocommerce_single_product_summary
hook.Then add your own action in at that priority to put in your message: