Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to login page in wordpress

I am new to wordpress. I am running wordpress setup on http://localhost/wordpress/. I am facing two problems right now:

  • Only the logged in users can access the site. So, I am trying to redirect the user from home page to login page using the following code which is somehow isn't working:

Path: wp-content/themes/twentysixteen/header.php

        <?php
            if(get_permalink() != wp_login_url() && !is_user_logged_in()){
                wp_redirect( wp_login_url() ); exit;
            }
        ?>

Since the above code wasn't working, I tried to move on by letting the user to login manually by clicking on the login button. Here is the working code:

<?php
    if(get_permalink() != wp_login_url() && !is_user_logged_in()){
        // wp_redirect( wp_login_url() ); exit;
?>
        <a href="<?php echo wp_login_url( get_permalink() ); ?>" title="Login">Login</a>
<?php
    }
?>
  • From above code, when user clicked on login he was redirected to login page and When the user is logs in, the page is redirecting to wordpress admin i.e wp-admin instead of home page i.e http://localhost/wordpress.

What I am trying to do is:

  • Redirect the user from home page to login page, if the user isn't logged in.
  • And then redirect the user from login page to home page instead of wp-admin, when user logs in.
like image 975
Mr_Green Avatar asked Mar 13 '23 06:03

Mr_Green


1 Answers

To redirect the user from homepage to login page, you can use Wordpress function is_user_logged_in,

https://developer.wordpress.org/reference/functions/is_user_logged_in/

if(!is_user_logged_in()) {
    wp_redirect( wp_login_url() );
}

To redirect user on homepage rather Dashboard, you can follow already posted solution on Stack overflow.

https://wordpress.org/support/topic/how-can-i-redirect-users-to-the-front-page-after-log-in

like image 172
Noman Ibrahim Avatar answered Mar 16 '23 03:03

Noman Ibrahim