wp_login_url() not working with redirect

I’m trying to show login link and redirect user to current page after login. The login works fine but the redirect is not working? It always redirects to home page even I can see ?redirect_to='redrect_link' with login link.

As per WP codex, it should redirect on login:
http://codex.wordpress.org/Function_Reference/wp_login_url

Read More

Here is my code:

$link_to_login = '<a href="' . wp_login_url( get_permalink() ) . '" title="Login">Login</a>';

Any reason, why is it not redirecting to current page on login? Any other solution? Thanks

Related posts

Leave a Reply

3 comments

  1. You’re probably calling get_permalink() outside the loop:

    Note that when used outside The Loop on a posts page (index, archive,
    etc.) without the ID parameter, it will return the URL of the last
    post in The Loop, not the permalink for the current page.


    Solution:

    To get the permalink outside of the loop you need to define the $post parameter:

    get_permalink( int|WP_Post $post, bool $leavename = false )

    $post int|WP_Post Optional

    Post ID or post object. Default is the global $post.


    Example:

    global $post;
    $post_id = $post->ID;
    $login_url = wp_login_url( get_permalink( $post_id ) );
    $link_to_login = '<a href="' . $login_url . '" title="Login">Login</a>';
    
    

    or

    $login_url = wp_login_url( get_permalink( get_queried_object_id() ) );
    $link_to_login = '<a href="' . $login_url . '" title="Login">Login</a>';
    

    Reference:

    P.S. If you’re using AJAX request, see this question: https://wordpress.stackexchange.com/questions/398569/get-the-url-of-the-page-from-which-an-ajax-request-has-been-launched-within-ajax