0

I am working on an area of my site for members. However, I need a link on my menu that when clicked it will take people to my login form then back to the page they were previously on. I need the same with log out.

Example: Bob logs in on page A. Bob has a successful login. Bob is returned to page A.

Bob clicks the logout link on page A. Bob is returned to page A after being logged out.

EDIT: The other question did not seem to have anyway to add a login logout link to the navigation menu. This is what I need acomplished. Thanks for your help.

1

Use wp_login_url() function with get_permalink() as a parameter, if a user is not logged in. Something like this:

<a href="<?php echo wp_login_url( get_permalink() ); ?>" title="Login">Login</a>

And wp_logout_url function with get_permalink() as a parameter, if a user is logged in.

<a href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a>

EDIT: instead of using 2 different functions, you may use

<?php wp_loginout(get_permalink()); ?>

that displays a login link, or if a user is logged in, displays a logout link

  • not sure about the use of get_permalink here as you might need that login link on pages that don't have a permalink. $_SERVER['RESQUEST_URI'] (+ the query string maybe) might be a more robust option. – Mark Kaplun Dec 1 '15 at 5:20
  • Even if you are on a page, get_permalink() will return the URL of this page. Don't worry :) – mukto90 Dec 1 '15 at 5:23
  • 1
    login page itself, (which might be a not interesting case here) do not have a permalink, other pages might have content for which the scheme of posts and taxonomies do not apply at all. And then there are the parameters, are you sure you should ignore them? (guess it might be different for different sites) – Mark Kaplun Dec 1 '15 at 5:30
  • Every page/post has a permalink. This function returns the URL of the SCREEN that you are currently viewing. – mukto90 Dec 1 '15 at 5:34
  • pages and posts are just the most used way to construct URLs, but not all sites use them for all of their URLs. Again the login page itself is a great example for that. – Mark Kaplun Dec 1 '15 at 5:41
0

This is the code that fixed my problem:

add_filter( 'wp_nav_menu_items', 'add_login_logout_link', 10, 2 ); 

function add_login_logout_link( $items, $args ) {
    $pageURL  = 'http://';
    $pageURL .= $_SERVER['HTTP_HOST'];
    $pageURL .= $_SERVER['REQUEST_URI'];

    ob_start();
    wp_loginout( $pageURL );
    $loginoutlink = ob_get_contents();
    ob_end_clean();
    $items .= '<li>'. $loginoutlink .'</li>';
    return $items;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.