WooCommerce check and redirect to login before checkout - wordpress

The default Woocommerce checkout behavior breaks a lot of web conventions by showing the "Create Account" boxes on the checkout page if it detects the user is not logged in. New users may not know what to do without any added instructions.
My desired sequence would be:
User Checkout > Check login >
Proceed to checkout if logged in.
Redirect to login/register page if not logged in > proceed to the checkout page.
This is EXACTLY the case in WooCommerce login redirect based on cart
However, what I feel uncomfortable is that, in the above case, once the user logged in, he/she will be redirected to the checkout page if the cart is not empty. If the user's cart is not empty, he/she will not be able to go to MyAccount at all even though he/she does not want to checkout yet.
Any idea on this one?

Try this no need to change core code
add_action('template_redirect','check_if_logged_in');
function check_if_logged_in()
{
$pageid = get_option( 'woocommerce_checkout_page_id' );
if(!is_user_logged_in() && is_page($pageid))
{
$url = add_query_arg(
'redirect_to',
get_permalink($pagid),
site_url('/my-account/') // your my account url
);
wp_redirect($url);
exit;
}
if(is_user_logged_in())
{
if(is_page(get_option( 'woocommerce_myaccount_page_id' )))
{
$redirect = $_GET['redirect_to'];
if (isset($redirect)) {
echo '<script>window.location.href = "'.$redirect.'";</script>';
}
}
}
}

In the second answer there is a problem, after loging in the user always redirects checkout page, it does not stand on my-account page until the cart become empty!!
This code redirects the user to my-account page for login instead of checkout if the user is not logged in, then after loging in it automatically redirects to checkout page.
STEP 1:
Add this code in function.php
add_action('template_redirect','check_if_logged_in');
function check_if_logged_in()
{
$pageid = get_option( 'woocommerce_checkout_page_id' );// your checkout page id
if(!is_user_logged_in() && is_page($pageid))
{
$url = add_query_arg(
'redirect_to',
get_permalink($pageid),
site_url('/my-account/') // your my acount url
);
wp_redirect($url);
exit;
}
}
STEP 2:
Add this code at the end of /wp-content/plugins/woocommerce/templates/myaccount/my-account.php
<?php
$quark_web_solution_redirect = $_GET['redirect_to'];
if (isset($quark_web_solution_redirect)) {
echo '<script>
window.location.href = "'.$quark_web_solution_redirect.'";
</script>';
}
?>

after reading this post and others in Stackoverflow, i came up with a simple solution (more than i thought at first) that is working for me... Maybe theres something i have missed up in the process, but i have tested several combinations and it works for me. So we want to:
Customer goes to checkout
If Logged In, continue to checkout. If not logged in, go to a page with login and register forms.
Once in this page, if customer logs in or register, continue to Checkout.
First, i created a custom page with [woocommerce_my_account] shortcode. Here i customized the texts etc... in the forms, so its a little bit different that my account page. URL path of this page is -> /iniciar-sesion-registrarse.
Then, i put this code in functions.php of my child theme:
function custom_woocommerce_login_redirect_to_checkout_page() {
// Caso 1: Usuario no identificado intenta acceder a Finalizar Compra
if ( !is_user_logged_in() && is_checkout() )
wp_redirect( get_permalink( get_page_by_path('iniciar-sesion-registrarse') ) );
// Caso 2: Si en la página de identificarse, el cliente ha accedido o se ha registrado, o tiene el carrito vacío, continuar a Finalizar Compra.
if ( is_page('iniciar-sesion-registrarse') ) {
if( is_user_logged_in() || WC()->cart->is_empty() ) {
wp_redirect( get_permalink( get_page_by_path('finalizar-comprar') ) );
}
}
}
add_action( 'template_redirect', 'custom_woocommerce_login_redirect_to_checkout_page' );
So in Case 1: If user is not logged in and tries to go to checkout, it redirects to my custom login page 'iniciar-sesion-registrarse'.
Then in Case 2: If user loggin or register in this page, normal my account page would be displayed in this page, then i redirect users who are logged in and are in this page to checkout. I also redirect them to checkout if someones access this custom page directly and has nothing in their carts (so woocommerce message: u cant checkout without items in ur cart is displayed).
This way, while loggin in or registering in this custom page, error messages will display normally as if it was real 'my-account' page, but once logged in, it will redirect to checkout.
I hope someone can tell me if i have missed something in the process. Thx

Actually had this problem today & now have a solution.
Context: our site has a separate user registration system than WooCommerce, so we didn't want a duplicative process prompting users to signup twice.
First I'll give the brief solution then list the full steps for my situation.
Brief solution: enable guest checkout, (trust me) enable account creation during checkout, automatically generate username and password (most important). Then disable in email settings the "New Account" message. Now "users" can checkout with account details auto-generated, but they never know about it and that information is essentially dumped.
Screenshot of my Accounts & Privacy settings. Please note I also disabled the "New Account" message triggered in the Email settings for WC.

Add this code in function.php
add_action('template_redirect','check_if_logged_in');
function check_if_logged_in()
{
$pageid = get_option( 'woocommerce_checkout_page_id' );
if(!is_user_logged_in() && is_page($pageid))
{
$url = add_query_arg(
'redirect_to',
get_permalink($pagid),
site_url('/my-account/') // your my acount url
);
wp_redirect($url);
exit;
}
}

Related

Message when redirected by a hook on wordpress

I am using a small code snipet to redirect non logged user from the shop page to the main page.
function my_redirect() {
//if you have the page id of landing. I would tell you to use if( is_page('page id here') instead
//Don't redirect if user is logged in or user is trying to sign up or sign in
if( !is_user_logged_in() && is_page('shop')){
echo 'Non logged user - You are redirected to the main page';
exit( wp_redirect( get_permalink(2604) ) );
}
}
add_action( 'template_redirect', 'my_redirect' );
This is working fine.
However I would like to prompt a message saying "You must be log to access the shop".
I don't know how to do it, my echo in the code do not display anything.
Any idea ?
Thx
You will never see the output of the echo because this action is triggered just before wordpress decides which template to load, so it's an echo in the middle of nowhere (and why the wp_redirect is inside and exit function?)

Unlogged user cannot see store and must go to login and successfully logged in users must be redirected to store

I am working on a Wordpress site with Woocommerce. I am using this function inside functions.php to redirect everyone who visits my store to login since it is a private area. Once the person logs in, they should be redirected to the store again. I have the following code implemented, which works for me to get all those trying to navigate my store to log in, I need to modify this code so that once logged in, it redirects me to the store page in woocommerce, in my case the page of the store is called "tienda".
To clarify: Users who are not registered or logged in, should not be able to see the store or cart or anything from woocommerce, I already implemented this with a wp-members plugin, if they try to navigate these woocommerce urls, they must go to login. When you have already logged in, you should go to the store, in my case you should not redirect to the previous link, but must inevitably go to the page called "tienda".
On the other hand, I would like to know if my function is missing something or is well built. Thank you!
function loggedoutuser_redirect() {
if (
! is_user_logged_in()
&& (is_woocommerce() || is_cart() || is_checkout())
) {
header('Location: ' . wp_login_url());
exit;
}
}
add_action('template_redirect', 'loggedoutuser_redirect');
function woocommerce_login_redirect_custom( $redirect, $user ) {
$redirect = wc_get_page_permalink( 'shop' );
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'woocommerce_login_redirect_custom', 10, 2 );
Paste this above snippet at the end of your active child theme functions.php file or else if you are good in plugin development then create a custom plugin.
Snippet Explanation:
Create a custom function to redirect after logged in
Fetch the shop URL using WooCommerce helper function wc_get_page_permalink( 'shop' ) and assign it to the variable $redirect
Then return the URL
Hook the custom function to the filter hook woocommerce_login_redirect
Note: You can check the user role inside our custom function then based on the role you can redirect it to the dashboard if he is administrator else to the shop page.

WooCommerce - Redirecting a User after They've Reset Their Password

I'm setting up a WooCommerce shop for a client and he has requested that the user be redirected back to the login form after the reset password form has been submitted.
Is this possible? Which function controls this?
Thanks in advance.
A much cleaner solution is to redirect using the woocommerce_customer_reset_password action:
function woocommerce_new_pass_redirect( $user ) {
wp_redirect( get_permalink(woocommerce_get_page_id('myaccount')));
exit;
}
add_action( 'woocommerce_customer_reset_password', 'woocommerce_new_pass_redirect' );
This code can be placed in functions.php.
Someone asked me about doing this and I think I'm going to talk them out of it, but here's what I came up with so that you could see the message and then be redirected in 5 seconds. Add a message/link to let them know you'll be redirecting. Plus, this will last through a WooCommerce upgrade if you add the template file to your theme
Add the form-lost-password.php template file to your theme and add the following code:
if ( $_GET[reset] = true && ( 'lost_password' == $args['form']) ) {
$my_account_url = get_site_url() . '/my-account';
echo "<script>window.setTimeout(function(){window.location.replace('$my_account_url')}, 5000)</script>";
}
If you dont want the time delay get rid of the window.setTimeout() and just use window.location.replace('$my_account_url').
I'm just facing the same question. I think the function that controls this is in the file woocommerce/includes/class-wc-form-handler.php. I changed the following line:
wp_redirect( add_query_arg( 'reset', 'true', remove_query_arg( array( 'key', 'login' ) ) ) );
with
wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
With that change, you get redirected to the my-account page, where the customer can log in, but of course there are two problems doing that:
The customer gets no message the the password recovery was successful
Doing a WooCommerce update, the file gets overwritten with the original file
Would be great, if someone could come up with a "update-secure" solution.
Best regards
Christoph

change homepage for logged-in users in wordpress

In wordpress i want a different homepage for logged-in users and those who are logged-out (simple changing the redirect url when somebody clicks on the title of my website). Is there a way of doing this by adding a code snippet in my themes functions.php? I tried:
add_filter('get_the_permalink','my_permalink_redirect');
function my_permalink_redirect($permalink) {
if( is_user_logged_in() ) {
global $post;
if ($post->ID == 1) {
$permalink = 'http://localhost/homepage-for-logged-users';
}
}
return $permalink;
}
unfortunately it doesn't work and it would be unhandy to change the function from localhost to my domain name when i upload the site to a live hosting. can somebody give me some advice? Thanks!
edit:I got it working with the pluging "login with ajax" where I could define redirects after logins and I putted this snippet in my functions.php.
// Redirect users who arent logged in and on a 404 to the home page for logged out users
function login_redirect() {
// Check to see if user in not logged in and on the home page for logged users
if(!is_user_logged_in() && is_404()) {
// If user is, Redirect to home page for logged out users.
wp_redirect(home_url('home-logged-out'));
exit;
}
}
// add the block of code above to the WordPress template
add_action( 'wp', 'login_redirect' );
*I made the pages for logged-in users private so logged-out users will see 404. Not a very clean method, but it works for now...
Set your default home page to the page logged in users should see.
Add this code to functions.php:
add_action('init', 'redirect_user');
// for users not logged in
function redirect_user(){
if( !is_user_logged_in() ) {
wp_redirect( 'http://www.YourSite.com/SomePage');
exit;
}
}
Logged in users will see what they should see, and those not logged in will be redirected.

Woocommerce/Wordpress - Redirect User Login to Homepage

I have searched for the answer to this, used plugins and still nothing works.
I would like users of my site to be redirected to the home page after they login/register.
Currently, the user logs in and is redirected to the my account page.
Woocommerce provides this code, but it failed to work for me:
/*
* goes in theme functions.php or a custom plugin
*
* By default login goes to my account
**/
add_filter('woocommerce_login_widget_redirect', 'custom_login_redirect');
function custom_login_redirect( $redirect_to ) {
$redirect_to = 'http://anypage.com';
}
I have also attempted to use the Peter's Redirect plugin but it does not work since woocommerce bypasses wp-login.php.
Thoughts?
You can download http://wordpress.org/extend/plugins/peters-login-redirect/ and replace this in the widget-login.php
<input type="hidden" name="redirect_to" class="redirect_to" value="<?php echo $redirect_to; ?>
with
<input type="hidden" name="redirect_to" class="redirect_to" value="<?php echo site_url('/wp-content/plugins/peters-login-redirect/wplogin_redirect_control.php/'); ?>" />
That way you can use peters login redirect to redirect globally and specific users using the woocommerce login widget.
Make sure you change "Use external redirect file. Set this to "Yes" if you are using a plugin such as Gigya that bypasses the regular WordPress redirect process (and allows only one fixed redirect URL). Then, set the redirect URL to %s" in the settings to "YES".
Hope this helps.
Use this code on functions.php
add_filter('woocommerce_login_redirect', 'wc_login_redirect');
function wc_login_redirect( $redirect_to ) {
$redirect_to = 'https://www.google.co.in/';
return $redirect_to;
}
That fix they provide only works if you are utilizing the login widget. All you need to do it redirect the user after logging in to your home page is to add this to your login form:
<input type="hidden" name="redirect" value="<?php echo get_home_url(); ?>" />
There has been a filter recently added to allow you to redirect after registration. Doing a redirect on login is as simple as Tomanow mentions above (putting it in form-login.php). Here is a link to the filter and some instructions for handling this on the registration form.
https://github.com/woothemes/woocommerce/commit/014e31952828377bf7a1ebf4e812a43d0bcefa67#commitcomment-3351995
Use this code on functions.php
add_action('wp_logout','go_home');
function go_home(){
wp_redirect( home_url() );
exit();
}
Do this:
Go to admin > Woocommerce > Settings > General
Find "Customer Accounts" under "Cart, Checkout and Accounts"
Uncheck "Prevent customers from accessing WordPress admin"
Save Changes and test!
You can set redirect according to user role. Given bellow the code for that redirection and I have developed a WooCommerce Login or Register Redirect plugin for entry level user or nor technical or no-programmer.
//Redirect users to custom URL based on their role after login
function wp_woo_custom_redirect( $redirect, $user ) {
// Get the first of all the roles assigned to the user
$role = $user->roles[0];
$dashboard = admin_url();
$myaccount = get_permalink( wc_get_page_id( 'my-account' ) );
if( $role == 'administrator' ) {
//Redirect administrators to the dashboard
$admin_redirect = get_option('admin_redirect');
$redirect = $admin_redirect;
} elseif ( $role == 'shop-manager' ) {
//Redirect shop managers to the dashboard
$shop_manager_redirect = get_option('shop_manager_redirect');
$redirect = $shop_manager_redirect;
} elseif ( $role == 'customer' || $role == 'subscriber' ) {
//Redirect customers and subscribers to the "My Account" page
$customer_redirect = get_option('customer_redirect');
$redirect = $customer_redirect;
} else {
//Redirect any other role to the previous visited page or, if not available, to the home
$redirect = wp_get_referer() ? wp_get_referer() : home_url();
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'wp_woo_custom_redirect', 10, 2 );
Also include this for standard WordPress login form logins that use wp-login.php:
add_filter('login_redirect', 'custom_login_redirect');
I use this filter and the one you have given, against the same filter function, and it catches the two places where a user may log in (WP and WC).
Also just noticed the obvious problem. You have this in your filter function:
$redirect_to = 'http://anypage.com';
but you need this:
return 'http://anypage.com';
$return_url is passed in from previous filters, so you can inspect it and decide whether to change it.
Edit:
Actually, I need to correct some of this. It looks like the woocommerce_login_widget_redirect filter is used to set the redirect parameter in the widget login form. This means it only fires when the user is not logged in and the widget login form is presented. It cannot be used to decide where to send the user after they have logged in.
The WP login_redirect filter fires after the user has logged in, and can modify any redirect_to URL sent with the login form to enable you to redirect the user to some other page.
In addition, the WooCommerce login widget does not handle the logins that you would assume it does. The login process is handled via AJAX in woocommerce-ajax.php You will see in there that the redirect URL is not passed through the woocommerce_login_widget_redirect filter and so cannot be modified. I'm going to raised this as a pull request with WooCommerce, because I believe it should be filtered.
https://github.com/woothemes/woocommerce/pull/2508

Resources