0

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.

  • If it were me I'd just add the HTML in my theme after the wp_nav_menu call but in the same wrapping element. It's easier to achieve and to my mind more semantically correct. – Andy Macaulay-Brook May 24 '16 at 20:55
  • Ah ok, so you're saying to just add in the element directly to the header.php template? – nickpish May 24 '16 at 20:59
  • If that's where you've got your nav, yes. If it's a downloaded theme then put your changes in a child theme so they aren't overwritten by an update. – Andy Macaulay-Brook May 24 '16 at 21:04
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.