Dynamically Add Menu Items in WordPress

One customization in membership website is to add login / logout link somewhere on the web page. Most common place to add this link is navigation menu. Login / logout menu item can’t be added via Appearance / Menus in admin panel, because it changes its content based on user “logged in” status.

To do so, we can leave the “login / logout” out of the menu setup in admin panel, and add it dynamically based on real-time user logged in status.

The following code does just that. It add new menu item(s) by using “wp_nav_menu_items” filter.

// Add Login / Logout menu item dynalically to primary navigation menu
function custom_add_loginout_link( $items, $args ) {
    if ($args->theme_location == 'primary'){
        if (is_user_logged_in()) {
            $items .= '<li><a href="'. wp_logout_url(home_url()) .'">Logout</a></li>';
        } else {
            $items .= '<li><a href="'. site_url('wp-login.php') .'">Login</a></li>';
        }
    }

    return $items;
}

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

In line 3, “primary” is the menu location slug registered to WordPress in register_nav_menus(). Change it to the correct name used in your theme.

In line 5, I redirect the user to home page after logout by using  wp_logout_url(home_url()).