Add Menu Item to Specific Menu in WordPress using Custom Code

One thing that is limited on the visual interface of menus is that you can only add links (pages, category, or custom links). What if you want to Add Custom Menu Item to a Specific WordPress Menu Item? Maybe you want to add a search bar, or log in/out link, logo, or anything else in a WordPress menu. Just because there is no visual interface, does not mean it is not possible. In this post, we will show you how you can utilize the wp_nav_menu_items hook to add custom items to all or specific WordPress menus. Let’s have a look at the following piece of code which shows the login/logout link on the primary menu location.

Add this code in your theme’s functions.php file of your active child theme (or theme).

add_filter( 'wp_nav_menu_items', 'add_logout_link', 10, 2 );
function add_logout_link( $items, $args ) {
    if (is_user_logged_in() && $args->theme_location == 'primary') {
        $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>';
    }
    elseif (!is_user_logged_in() && $args->theme_location == 'primary') {
        $items .= '<li><a href="'. site_url('wp-login.php') .'">Log In</a></li>';
    }
    return $items;
}

Leave a Comment

Scroll to Top