Add a ‘Logout’ button
-
Hello,
I triy to add a ‘logout’ button on the main nav menu under ‘account’ parent menu. But, the button does not rendor.
- At Appearance > Menus, I add ‘account’ page to the active menu. (link enabled)
- I add a code snippet
The code here;
function my_insert_primary_nav_login_link( $items, $menu, $args ) {
if( is_admin() )
return $items;
// Bail out if this menu isn'tmain-menu
orMain Menu
is being loaded in the dashboard.
if( $menu->slug !== 'main-menu' || is_admin() )
return $items;
// Find the ID of the Page with the slugaccount
in the menu items.
foreach( $items as $item ) {
if( $item->post_type !== 'page' || $item->post_name !== 'account' )
continue;
$account_page_id = $item->ID;
break;
}
// Bail if theaccount
page is not in this menu.
if( ! isset( $account_page_id ) )
return $items;
$logged_in = is_user_logged_in();
$link_title = __( $logged_in ? 'Log In' : 'Log Out', 'oceanwp' );
// Insert a new WP_Post object for the link.
$items[] = new WP_Post(
(object) [
'ID' => 'user-login',
'menu_item_parent' => $account_page_id,
'classes' => [ 'account-auth-link' ],
'type' => 'virtual',
'object' => 'virtual',
'title' => $link_title,
'attr_title' => $link_title,
'url' => $logged_in ? wp_logout_url() : wp_login_url(),
]
);
return $items;
}
add_filter( 'wp_get_nav_menu_items', 'my_insert_primary_nav_login_link', 10, 3 );If you could review the code, I would really appreciated.
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- You must be logged in to reply to this topic.