0

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?

1 Answer 1

1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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