Sam
(@sammazza)
interesting… I have a similar problem ob_get_contents() returns empty string. I am trying to insert a longin/logout to my menu following example in
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {
if ( $args->theme_location == 'primary-menu' ) {
ob_start();
wp_loginout('index.php');
$loginoutlink = ob_get_contents();
ob_end_clean();
$items .= '<li>'. $loginoutlink .'</li>';
}
return $items;
}
noting gets added… ?!
Thanks
Sam
(@sammazza)
I should have mentioned I am using Mystile and wooCommerce – all the latest versions.
Can you try this code…
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {
if ( $args->theme_location == 'primary-menu' ) {
$loginoutlink = wp_loginout('index.php', false);
$items .= '<li>'. $loginoutlink .'</li>';
}
return $items;
}
Sam
(@sammazza)
thanks that worked. Is the code with ob_get_content just old? Why did your code work?
i’d like to mention, there is a slight side effect; if I use this menu style link to log-out, it seems it does not use the wooCommerce logout procedure so:
1. after log out I am on different page (wooCom redirect not working)
2. even though I have woocommerce set to ’empty cart on log-out’, cart does not empty.
Is there a way to avoid these side effects or to insert a proper wooCommerce logout in the menu?
Thanks
In this context you do not need to use ob_
first the output buffer is started by WordPress so no need for a ob_start
ob_get_contents would be to get what WordPress has already output in the buffer which you do not need to do in your case since you are just adding an entry to $items
wp_loginout(‘index.php’, false); Adding the , false here tells WordPress not to output (echo) the link but instead return it as a string…
Voila 😀
Regarding woocommerce i never used it but, from what you are saying it seems to be using a different login/logout procedure from WordPress…
My advise here would be to replace the wp_loginout by an api call to woo commerce to get their link… if they have that…
Also the redirect as you can see you indicate index.php here: wp_loginout(‘index.php’, false); so that where it redirects… If you want to use this api and want to redirect elsewhere, just put another link in there… You can set it to wp_loginout(”, false); to redirect to the default redirect link… See if it would do the woo redirection in that case…
Good luck with all that…
Sam
(@sammazza)
Thanks for pointing me in the right direction. I got this modified to work on wooCommerce. Here is the code:
if (is_user_logged_in()) {
$items .= '<li><a href="'. get_permalink( woocommerce_get_page_id( 'logout' ) ) .'">Log Out</a></li>';
}
else {
$items .= '<li><a href="'. get_permalink( woocommerce_get_page_id( 'myaccount' ) ) .'">Log In</a></li>';
}