Sometimes, you may need to add your own text, icons, images, search forms, links with special attributes or functions to the before or after the navigation menus.
We can make use of wp_nav_menu_items filter to add additional custom menu items to the menu bar, which can be appended or prepended on the other menu items generated by WordPress.
Here’s the example code, to be added into active theme’s functions.php file:
add_filter('wp_nav_menu_items','tj_custom_menu_function',10,1); function tj_custom_menu_function ( $nav ) { $custom_function = 'Enter Custom Menu Items in HTML'; return $nav.$custom_function; }
For example, the following will prepend an image before the navigation menu as a prefix:
add_filter('wp_nav_menu_items','tj_custom_menu_function',10,1); function tj_custom_menu_function ( $nav ) { $custom_function = '<img src="img/image_name.jpg">'; return $custom_function.$nav.; }
If you have multiple navigation menu, you can add in the condition to filter out unwanted navigation menu, and add and display the additional menu items on your chosen menu only. To do so, we need to pass the second parameter provided by the wp_nav_menu_items filter and check the theme_location. The following example assumes that the navigation menu that you want to add custom items to is called “primary”.
add_filter('wp_nav_menu_items','tj_custom_menu_function',10,2); function tj_custom_menu_function ( $nav, $args) { if( $args->theme_location == 'primary' ) $custom_function = 'Enter Custom Menu Items in HTML'; return $nav.$custom_function; } }
To find out what’s the name of theme_location for a navigation menu, search for register_main_menus() or register_nav_menus() function in the theme files.