Add Custom Menu Link Via Code In WordPress

We can add our custom menu link any menu location via code. For this, we have “wp_nav_menu_items” filter which help us to add the custom menus.

add_filter( ‘wp_nav_menu_items’, ‘add_custom_nav_menus’, 10, 2 );

this filter returns two parameters, $items and $args.

$items is a variable which contains the menu list which we have set from wp-admin->menus.

$args is an array which contains the arguments data like menu name, menu link, menu order etc.
How to use this filter ?

add_filter( 'wp_nav_menu_items', 'add_custom_nav_menus', 10, 2 );
function add_custom_nav_menus($items, $args ) {
 global $wpdb;
   if(in_array($args->theme_location,array('primary') )) {
     if(is_user_logged_in()):
         $items .= '<li class=”menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children has_children”>';
         $items .= '<a href=”'.get_site_url().'/my-account/” >My Account</a>';
         $items .= '<p class=”dropdownmenu”></p>';
         $items .= '<ul role=”menu” class=”sub-menu”>';
         $items .= '<li class=”menu-item menu-item-type-custom menu-item-object-custom”>';
         $items .= '<a href=”‘.wp_logout_url().'” >Logout</a>';
         $items .= '</li>';
         $items .= '</ul>';
         $items .= '</li>';
    else:
         $items .= '<li class=”menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children has_children”>';
         $items .= '<a href=”‘.get_site_url().’/login/” >Login</a>';
         $items .= '<p class=”dropdownmenu”></p>';
         $items .= '<ul role=”menu” class=”sub-menu”&gt';
         $items .= '<li class=”menu-item menu-item-type-custom menu-item-object-custom”>';
         $items .= '<a href=”‘.get_site_url().’/register/” >Register</a>';
         $items .= '</li>';
         $items .= '</ul>';
         $items .= '</li>';
    endif;
 }
 return  $items;
}

in above code, I’m adding for custom menu links which are login, register, my account and log out.

Why am I using custom menu ?

I want that if the user is login then only my account and log out menu should be shown. and if a user is not logged in then only login and register menu should be shown.

this can be done via wp-admin because I can’t apply a logical condition on that.

now by this if(in_array($args->theme_location,array(‘primary’) )) condition i am adding custom menu only on primary menu. the keyword “primary” is not fixed it always changes as per your theme. you need to check the menu location in which you want to add the custom menu links.

now as you can in code, i am just appending the HTML code in $items variable and returning the $items variable in this function.

You can apply our own logic to adding the custom menu as per your need.

Thanks for your reading.