0

I am developing a WP site locally on Xampp.

I am using the following code to add a styled login/out button to the sidebar:

 add_shortcode( 'my_login', 'my_login' );
    function my_login() {
    if ( is_user_logged_in() ) 
    return '<a href="'.wp_logout_url( get_permalink() ).'" title="Logout"   class="button login">LOG OUT</a>';
                     else 
                        return '<a href="'.wp_login_url( get_permalink() ).'" title="Login" class="button login">LOG IN</a>';
                    }

My site has 6 pages linked to the main nav. One is for the blog and another is a bbpress forum. If I login/out on 4 of these pages the code works as expected. That is if I visit the page then log in I am returned to that page. If I log out on that page I am returned to it also.

However, when on the blog main page, or a blog post, and I log in I am taken (always) to the oldest post in the blog (the one that displays last on the blog main page) What ever page I log out from in the blog same occurs. I am taken to the last post.

Same problem occurs if I am on the forum index page or a forum topic. When I log in I am taken (always) to the forum at the bottom of the forum index. What ever forum page I log out from same problem occurs.

Basically I just want my login/out to function as it should. Whatever page a person is on when they log in they are taken back to that page.

I have tried deactivating all of my plugins and the problem remains so it is not plugin related.

Any help anyone can provide to resolve this is greatly appreciated.

Thank in advance for any assistance.

Kind Regards

Max

1

get_permalink will fetch the URL of the current post within a loop. If you call it on an archive page, then what WP thinks is the "current post" is actually the first post that you are about to loop through and so you end up with that post's permalink rather than the current page's URL.

I've not found a better way than this, which effectively rebuilds the URL from the current request:

global $wp;
$current_url = home_url( add_query_arg( array(), $wp->request ) );

Doing it this way rather than messing with $_SERVER, which I've seen in various online posts, at least ensures that you easily get your canonical hostname & your protocol right.

  • Andy. Thanks for taking the time to provide an answer. However, I am unsure of how your suggestion can be incorporated into my shortcode snippet. (Yes I am a newb...) – khunmax Aug 13 '16 at 8:29

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.