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

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.

Related

How to redirect user to another page if the user is logged in - WordPress Elementor Page Builder

I have created a registration form using Elementor Page Builder. Now, I want to redirect the user to a different page if he/she is trying to access that registration page after logging in.
Is there any Elementor hook available for that? I know the WordPress function called is_user_logged_in().
function my_logged_in_redirect() {
if ( is_user_logged_in() && is_page( 12 ) )
{
wp_redirect( get_permalink( 32 ) );
die;
}
}
add_action( 'template_redirect', 'my_logged_in_redirect' );
You should get the ids of the page where the form is and the id of the page you want to redirect the user to.
Code goes in your child theme functions.php file
Reference: here
The 'Content Area Not Found' error might appear on Elementor designed sites when you use that snippet and try to edit page of ID 12 (in your example) in certain cases.
To avoid this, add the following code before the if-statement of your snippet:
if ( \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
return;
}

Wordpress redirect to login page if user is not logged in

I need to force users to login before they can see browse my site. For new users Access should only be allowed to the my-account page which is my login url i.e. example.org/my-account
Below is what i've done so far
add_action('wp','force_register' );
function force_register() {
$loggedin = is_user_logged_in();
$pagename = get_query_var('pagename'); //get current page name
if(strcmp("my-account",$pagename) != 0){ //if the user is looking at any other page other than my-account page
if(!$loggedin){ //if the user is not logged in
wp_safe_redirect( "/my-account", 302 ); //redirect to the login page
exit;
}
}
The browser can't redirect and complains about too many redirects
What am I missing ?
Before WordPress does any routing, processing, or handling. It is run in the main() WP method in which the $query_args are passed to parse_request(), as well as when send_headers() , query_posts(), handle_404(), and register_globals() are setup. This is caused for your issue, You may use init instead of wp hook. more about wp hook.

WooCommerce check and redirect to login before checkout

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;
}
}

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