Support » Fixing WordPress » wp_nav_menu() – header menu – before after not working – fix(ish)

  • I thought I’d post this to help folk, as I needed this to work.

    If you’re using a theme that uses wp_nav_menu() in the header.php and you want the before/after arguments to work.

    Basically they don’t work because the menu falls back to wp_page_menu() as it is not a registered menu, and wp_page_menu() doesn’t contain the arguments ‘before’ and ‘after’ but if you don’t want to go through the process of registering the menu and creating it in Appearance > Menu etc. Which is a bit of faff.

    Simply add the arguments to wp_page_menu() found in wp-includes/post-template.php

    You will need to first add the argument to the $defaults i.e.:

    $defaults = array('sort_column' => 'menu_order, post_title', 'menu_class' => 'menu', 'echo' => true, 'link_before' => '', 'link_after' => '', 'after' => '');

    Then add the args to the outputs for if is_front_page and for $output

    $menu .= '<li ' . $class . '>'. $args['after'] . '<a href="' . home_url( '/' ) . '" title="' . esc_attr($text) . '">' . $args['link_before'] . $text . $args['link_after'] . '</a>';

    Then in your wp_nav_menu() in header.php add the argument e.g.
    <?php wp_nav_menu( array( 'theme_location' => 'primary', 'after' => '<span class=\'arrowdown\'> </span>' ) ); ?>

    Then you should be good to go.

Viewing 4 replies - 1 through 4 (of 4 total)
  • esmi

    (@esmi)

    Forum Moderator

    Simply add the arguments to wp_page_menu() found in wp-includes/post-template.php

    No! Never, ever, edit WordPress core scripts. And do not encourage others to do so. Editing core scripts can bring down your entire site and/or open security holes for hackers to use.

    they don’t work because the menu falls back to wp_page_menu()

    So create a custom callback function for your nav menu via your theme.

    Told! Fair enough.

    Can I ask a question though? Do you know why the arguments are not included in wp_nav_menu() ?

    Thanks,

    esmi

    (@esmi)

    Forum Moderator

    Because wp_nav_menu – by itself – does not generate anything. It’s really a kind of alias for either wp_page_menu (if there is no custom menu and no custom fallback), the custom menu itself or a custom callback. wp_page_menu does include link_before and link_after parameters but they just so happen to be set to empty string by default.

    One way of addressing this without creating a whole custom menu callback is to use something like:

    function my_page_menu_args( $args ) {
    	$args['link_before'] = '<span>';
    	$args['link_after'] = '</span>';
    	return $args;
    }
    add_filter( 'wp_page_menu_args', 'my_page_menu_args' );

    Thanks for the quick response and explanation.

    Appreciated.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘wp_nav_menu() – header menu – before after not working – fix(ish)’ is closed to new replies.