WordPress.org

Ready to get started?Download WordPress

Forums

how to auth_redirect to specific page (6 posts)

  1. janmalagucute
    Member
    Posted 1 year ago #

    Hi,

    I want to redirect non logged in users to my custom registration page.

    I did some searching and it looks like auth_redirect is similar to what I needed but my problem is auth_redirect redirects the user to default wp login page.

    Is there a way to redirect all non logged in users to a specific page?

    Thanks

  2. wpismypuppet
    Member
    Posted 1 year ago #

    Place this in your theme's header.php file at the very top:

    <?php
    	if( !is_user_logged_in() ) {
    		wp_redirect('http://somepagehere');
    		exit;
    	}
    ?>
  3. wpismypuppet
    Member
    Posted 1 year ago #

    You can also add this to your functions.php file instead of what I said before:

    function admin_redirect() {
       if ( !is_user_logged_in()) {
           wp_redirect( home_url('/{custom page goes here}/') );
           exit;
       }
    }
    add_action('get_header', 'admin_redirect');

    Might be a cleaner approach

  4. ngaireackerley
    Member
    Posted 8 months ago #

    Hello,

    I'm having a similar issue - not sure if there was a solution or not. It seems pretty simple to me, but I think I'm missing something obvious.

    Basically I have private posts that when the user clicks 'Read more' I want it to check if they are logged in, if not they are sent to a custom login page, then after they login it redirects them back to the single.php that they wanted to go to.

    With your current solutions above (and variations I've found), you get to the custom login page and can login then you are kept on that same page rather than going back to the original post.

    I had been using this in my functions.php, but it keeps the user on the custom login page:

    $subRole = get_role( 'subscriber' );
    $subRole->add_cap( 'read_private_posts' );
    
    function redirect_to_login() {
      global $wp_query,$wpdb;
      if (is_404()) {
        $private = $wpdb->get_row($wp_query->request);
        if( 'private' == $private->post_status  ) {
          wp_safe_redirect(home_url(get_permalink(9)));
          exit;
    	//auth_redirect();
        }
      }
    }
    add_action('template_redirect', 'redirect_to_login');

    However, auth_redirect works perfectly, but ideally I want to be using this custom login page instead of the main WordPress login.

    Is this even possible or should I just been changing the main WordPress login and use the auth_redirect?

    Many Thanks

  5. wpismypuppet
    Member
    Posted 8 months ago #

    @ngaireackerley,

    For cases like you are describing, I have use this as a solution:

    <?php
    	/**
    	 * Template Name: Login
    	 * The template for Employee Login form
    	 **/
    	if(have_posts()) :
    		get_header();
    		// If the user is logged in, show them the content
    		if( is_user_logged_in() ) :
    			while(have_posts()) :
    				the_post();
    				the_content();
    			endwhile;
    		// If the user is not logged in, force them to log in
    		else :
    			wp_login_form();
    			echo '<p id="loginnav">';
    			wp_register( '', ' | ' );
    			echo '<a href="';
    			bloginfo( 'wpurl' );
    			echo '/wp-login.php?action=lostpassword" title="Password Lost and Found">Lost your password?</a></p>';
    		endif;
    		get_footer();
    	else :
    		header( 'Location: ' . esc_url( home_url( '/' ) ) . '/404' );
    	endif;
    ?>

    This is a simple page template that will show the user the content, but only if they are logged in. If not, it will show the login form (or a custom one if you prefer). Once the form is submitted, they will immediately see the content since they are never redirected away from the page in the first place.

    All you have to do is create a page (template-login.php for example), paste in the code above and save the file. Then, on the pages that require the user to be logged in, simple select this "Login" from the template drop down.

  6. ngaireackerley
    Member
    Posted 8 months ago #

    Thanks, but I'm not sure that was what I was trying to explain.

    I ended up pretty much sorting it out, still tightening it up, but with plenty of research from various sites this is what I came up with - thought I'd share if it is of any use to anyone or if anyone can improve on it.

    Basically, if you have a private post, you click 'Read more' this code directs the user to the custom login page (get_permalink(9)) and then upon correct login redirects them to the full post. I've tweaked it for incorrect logins/errors and redirects upon logout.

    For the template file:

    if ( ! is_user_logged_in() ) { // Display WordPress login form:
    	//check if the user needs to be redirected, if not keep on current page
    	if   (!isset($_GET['redirect_to'])) {
        $args = array(
            'form_id' => 'loginform-custom',
            'label_username' => __( 'Username' ),
            'label_password' => __( 'Password' ),
            'label_remember' => __( 'Remember Me' ),
            'label_log_in' => __( 'Log In!' ),
            'remember' => true
            );
        //if do need redirecting get the past url
    	} else {
        $args = array(
        	'redirect' =>  $_GET['redirect_to'],
            'form_id' => 'loginform-custom',
            'label_username' => __( 'Username' ),
            'label_password' => __( 'Password' ),
            'label_remember' => __( 'Remember Me' ),
            'label_log_in' => __( 'Log In!' ),
            'remember' => true
        );
    }
    if(isset($_GET['login']) && $_GET['login'] == 'failed') { ?>
    <div id="login-error">
    <p>Login failed: You have entered an incorrect username or password, please try again.</p>
    </div>
    <?php } wp_login_form( $args ); ?>
        <a href="<?php echo wp_lostpassword_url( get_permalink() ); ?>" title="Lost Password">Lost Password</a>
    	<?php } else { // If logged in:
    	    wp_loginout( get_permalink() ); // Display "Log Out" link.
    	}
    }

    For the functions.php file:

    // Subscriber Login functionality to see private posts
    $subRole = get_role( 'subscriber' );
    $subRole->add_cap( 'read_private_posts' );
    
    //login via custom login page
    function redirect_to_login() {
      global $wp_query,$wpdb;
      if (is_404()) {
        $private = $wpdb->get_row($wp_query->request);
        if( 'private' == $private->post_status  ) {
    		$url = add_query_arg('redirect_to', $_SERVER['REQUEST_URI'], site_url(get_permalink(9)));
    		wp_redirect($url);
    		exit;
    	}
    } }
    add_action('template_redirect', 'redirect_to_login');
    
    //failed login attempts
    function custom_login_failed( $username )
    {
        $referrer = wp_get_referer();
    
        if ( $referrer && ! strstr($referrer, 'wp-login') && ! strstr($referrer,'wp-admin') )
        {
            wp_redirect( add_query_arg('login', 'failed', $referrer) );
            exit;
        }
    }
    add_action( 'wp_login_failed', 'custom_login_failed' );
    
    function custom_authenticate_username_password( $user, $username, $password )
    {
        if ( is_a($user, 'WP_User') ) { return $user; }
    
        if ( empty($username) || empty($password) )
        {
            $error = new WP_Error();
            $user  = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
    
            return $error;
        }
    }
    add_filter( 'authenticate', 'custom_authenticate_username_password', 30, 3);
    
    function custom_login_form_to_login_page( $content )
    {
        if ( is_page('registerlogin') && in_the_loop() )
        {
            $output = $message = "";
            if (! empty($_GET['action']) )
            {
                if ( 'failed' == $_GET['action'] )
                    $message = "There was a problem with your username or password.";
                elseif ( 'loggedout' == $_GET['action'] )
                    $message = "You are now logged out.";
                elseif ( 'recovered' == $_GET['action'] )
                    $message = "Check your e-mail for the confirmation link.";
            }
    
            if ( $message ) $output .= '<div class="message"><p>'. $message .'</p></div>';
            $output .= wp_login_form('echo=0&redirect='. site_url());
            $output .= '<a href="'. wp_lostpassword_url( add_query_arg('action', 'recovered', get_permalink()) ) .'" title="Recover Lost Password">Lost Password?</a>';
    
            $content .= $output;
        }
        return $content;
    }

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags