WPTrick : Add new element into wp menu

A simple trick to add new element into your wp menu.In this case I want to add custom search form to may

Just add this codes to your wp code I usually put in in functions.php


<?php

// Filter wp_nav_menu() to add additional links and other output
function custom_nav_menu_items($items, $args) {

 $search = '<li id="search">';
 $search .= custom_searchform();
 $search .= '</li>';
 $items = $items .$search;

return $items;
}
add_filter( 'wp_nav_menu_items', 'custom_nav_menu_items', 10, 2 );

function custom_searchform(){
 $search = get_search_query();
 if($search) $search_text = $search;
 else $search_text = "Search";

 $form = '<form method="get" id="searchform"  action="'.get_bloginfo('home').'">';
 $form .= '<fieldset>';
 $form .= '<input type="text" value="'.$search_text.'"  name="s" id="s"  />';
 $form .= '<input type="hidden" id="searchsubmit" />';
 $form .= '</fieldset>';
 $form .= '</form>';

 return $form;
}

?>

Method above will add search form to all wp menu. So how about if I only want to add to specific menu location?

Here we goes


<?php

# apply only ini 'header-menu' location

if($args->theme_location == 'header-menu'){
 $search = '<li id="search">';
 $search .= rh_searchform();
 $search .= '</li>';
 $items = $items .$search;
 }

?>

Finish,
-rmh-

  • http://www.athanassiadis.se Georgios

    Great job man, just what I was looking for! I passed a widget-area to the menu so the client can add whatever they want to the menu!

    Keep up the good work!

  • marc

    using atahualpa wp theme, using wp menu to design one of two menu bars in theme. Currently the default wp menu only lets me select from pages and categories. Don’t want use the widget for search categories in sidebar or header, prefer it to be a drop down in the menu bar thats just below my header image. WP Menu only lets me select individual categories as tabs. Also want to add Search Tags as a drop down using the WP Menu. Will using your code above in my theme display Tags for me to select to add to the menu? My custom Menu will look like this HOME ABOUT HOW TO SEARCH CATEGORIES SEARCH TAGS. Can the later two be done using your code? Right now can only select individual categories using WP Menu when I need “search categories” to drop down all from the menu just as I need “search tags” to display all in a drop down when someone clicks on the menu tab. Thanks in advance for your prompt reply.

  • http:ronggur.com ronggur

    @marc : Hmm, I’m not really sure for what you want but I think it is possible
    @Georgios : Thank you