Login/Logout field in menu bar is out of place and

2019-08-31 03:23发布

问题:

The past two days I have been trying to learn how to add a nice login/logout/register field into the top menu bar of my site. I just recently began familiarizing myself with editor. I dug this code up here in stackoverflow. I like the way it looks and I'm hoping to tweek it a bit.

    /* Custom Login Menu Field */
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);

function add_login_logout_link($items, $args) {
// start buffering
ob_start();
// this is the actual form function
wp_login_form($args); // $args optional see below ..
// get buffering
$loginoutform = ob_get_contents();
// clean buffering
ob_end_clean();
$items .= $loginoutform ; // concatenate buffering with items ...
return $items;
}

What I would like to do is have the login field area centered horizontally in the middle of the top/main menu bar. As you can see it is currently all the way to the right and stretches out the whole thing. When I use it- it does log me in, but does not switch to a "logout" option when signed in.

If anyone has any knowledge in this area on how I could add or modify my starter code I would be very grateful. Best regards- Cypher.

Site: cypherbeats.com Theme: Jarvis (latest) Code was added into functions.php

回答1:

At time of writing I cannot see this login bar you speak of. So cannot say whether your code works.

In your code you can use the function is_user_logged_in() as a conditional to check whether the visitor is logged in. Therefore you can use it to decide whether to output the login or logout code. The wp_loginout() function appears to display a logout button. So something like this coud work:

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

function add_login_logout_link($items, $args) {
// start buffering
ob_start();
// this is the actual form function
if( !is_user_logged_in() )
    wp_login_form($args); // $args optional see below ..
else
    wp_loginout();
// get buffering
$loginoutform = ob_get_contents();
// clean buffering
ob_end_clean();
$items .= $loginoutform ; // concatenate buffering with items ...
return $items;
}

Warning I haven't tested this and is just a suggestion to start you off.

Here is an alternative approach that might be handy. First install this plugin: https://wordpress.org/plugins/nav-menu-roles/ Then create a login link which is only visible to logged out users and a logout link that is only visible to logged in users. You could then write some javascript which causes the login form to popup in a lightbox when you press the login button. I use this approach at https://ptofchoice.com.au/