Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Im trying to replace my template's primary menu through a plugin so that I don't have to make changes to the header.php.

I found this code in another question answered here in 2011 (Replacing WordPress menu functionality with a plugin)

add_filter('wp_nav_menu', 'my_menu_func');
function my_menu_func(){
  print "Testing 123";
}

It worked but it replaced both my top primary menu and the widget side menu.

How can I specify which menu to target when using the filter?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

You could try the following code snippet to override the primary menu:

/**
 * Override the primary menu.
 *
 * @param string  $nav_menu The HTML content for the navigation menu.
 * @param array   $args     Array of wp_nav_menu() arguments.
 * @return string $nav_menu
 */

function wpse_150003( $nav_menu, $args )
{
    //Override the primary menu:
    if( 'primary' === $args->theme_location )
        $nav_menu = 'My new menu';

    return $nav_menu;
}

add_filter( 'wp_nav_menu', 'wpse_150003', PHP_INT_MAX, 2 );

where we find the input arguments info from the source.

Notice that we return the $nav_menu value, instead of echoing it.

You could also filter my other attributes, for example menu_id.

You might also consider these filters:

  • wp_nav_menu_items
  • wp_nav_menu_{$menu->slug}_items

I hope this helps.

share|improve this answer
    
That did it for me, thanks a lot! –  user54409 Jun 19 at 13:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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