I've been researching here and on other dev/WP sites to find the best solution for adding what is effectively a custom element to the navigation menu, and it seems like there are many approaches. Ultimately, I'd like a add a "Newsletter" item to the primary navigation menu, that would either include a form field directly in the menu to collect email addresses, or some kind of drop-down, into which the address can be entered.
One option seems to be using the Walker Class with wp_nav_menu
; or using add_last_nav_item
as suggested here. The only issue with the latter option is that I'd likely prefer to add this custom element in a position on the nav bar before the last item. Finally, I've also contemplated creating a custom widget and using a plugin to add the widget to the navigation bar.
Does anyone have any recommendations for adding this custom element to the nav menu? Any suggestions are most appreciated.
I've been researching here and on other dev/WP sites to find the best solution for adding what is effectively a custom element to the navigation menu, and it seems like there are many approaches. Ultimately, I'd like a add a "Newsletter" item to the primary navigation menu, that would either include a form field directly in the menu to collect email addresses, or some kind of drop-down, into which the address can be entered.
One option seems to be using the Walker Class with wp_nav_menu
; or using add_last_nav_item
as suggested here. The only issue with the latter option is that I'd likely prefer to add this custom element in a position on the nav bar before the last item. Finally, I've also contemplated creating a custom widget and using a plugin to add the widget to the navigation bar.
Does anyone have any recommendations for adding this custom element to the nav menu? Any suggestions are most appreciated.
Just to answer the direct question of where you might hook in to add to your nav menu, this technique is all over the web, mainly in the context of appending a search box to the nav.
If the theme location for your menu is main-nav
then this will add an extra list item to the menu list items.
add_filter('wp_nav_menu_items', 'add_signup_form', 10, 2);
function add_signup_form($items, $args) {
if( $args->theme_location == 'main-nav' )
$items .= '<li><form>Signup form in here</form></li>';
return $items;
}
As I said in my comments above, I don't think this is very semantic HTML and I guess the popularity around the web of this technique is due to that hook being almost the only one when nav menus were introduced.
And if you're in a position to edit theme files to put in this hooked function, then you may as well edit the header file(s) and put in more meaningful HTML to achieve what you want.
You can only really append rather than insert using this hook, but again I'd feel that inserting a form into the navigation was unsemantic myself.
header.php
template? – nickpish Commented May 24, 2016 at 20:59