Wordpress - Redirect to referring page after logging in

I'm not sure I understand your setup, but here are few ideas:

A) Display a login link with the redirect_to parameter set:

You could add the following to your custom template pages:

if( ! is_user_logged_in() )
{
    printf( '<a href="%s">%s</a>', 
        wp_login_url( get_permalink() ),
        __( 'You need to login to view this page!' )
    );
}

This will generate a login link, for anonymous visitors, with the current page in the redirect_to GET parameter.

B) Redirect to the wp-login.php with the redirect_to parameter set:

Notice that the call to wp_redirect() must happen before the HTTP headers are sent.

We can call it within the template_redirect hook:

add_action( 'template_redirect', 
    function()
    {
        if( ! is_user_logged_in() 
            && is_page( array( 'member-page-1', 'member-page-2' ) ) 
        )
        {
            wp_safe_redirect( wp_login_url( get_permalink() ) ); 
            exit();
        }
    }
);

where we restrict the access to pages with the slugs member-page-1 and member-page-2.

C) The native login form (in-line):

Another option would be to include the native login form, directly into the page content:

add_filter( 'the_content', function( $content ) {

    if( ! is_user_logged_in() 
        && is_page( array( 'member-page-1', 'member-page-2' ) ) 
    )
        $content = wp_login_form( array( 'echo' => 0 ) );

    return $content;
}, PHP_INT_MAX );

where we restrict the access to pages with the slugs member-page-1 and member-page-2.

Notice you would have to take care of the archive/index/search pages.

Update: I simplified it by using the wp_login_url() function.


Usgin get_permalink(), as suggested in the accepted answer, will work only if you are in a post (of any type) but it won't work, for example, if you are in a category archive. To make it work anywhere, the current URL is needed, not matter what type of content we are seeing.

To get the current URL in WordPress we can get the current request from the global $wp object and append it to the site url using add_query_arg(). We can use the result in the redirect_to parameter of wp_login_url() function:

wp_login_url( site_url( add_query_arg( array(), $wp->request ) ) );

The same approach can be used with wp_logout_url() if needed:

wp_logout_url( site_url( add_query_arg( array(), $wp->request ) ) );

Tags:

Redirect

Login