• Hi all.

    I’m trying to figure out (with my non-programmer self) how I can wrap all specific instances of a single word in the top-level list of links in wp_nav_menu in a span.

    Ex:
    The list of top-level links are:
    Our Community
    Our Officials
    Our Departments
    … etc.

    I want to wrap each instance of the word ‘Our’ with a span & a class, so that it can be styled differently (italicized).

    I have been able to sort of figure this out, using this code in my header.php:

    <?php
    	$menu = wp_nav_menu(
    	array( 'theme_location' => 'primary-menu', 'container' => '', 'echo' => false ));
    	$menu = str_replace("Our", "<span class='our'>Our</a>", $menu);
    	echo $menu
    ?>

    Unfortunately, it doesn’t work 100% as I’d like. It DOES wrap the word ‘Our’ in a span with a class of ‘our’. But it also strips the second word out of the anchor tag completely so it’s no longer part of the link, seemingly adding an extra anchor end. I can’t figure out why this is. Any help?

    So what originally was this:
    <a href="http://nameofsite.com/departments/">Our Departments</a>
    then becomes this:
    <a href="http://nameofsite.com/departments/"><span class='our'>Our</a> Community</a>

    Thanks! (also I’m not sure if Themes and Templates is the right section for this…)

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi daledude,

    Easy fix….

    In your code, you have closed the span with a closing anchor tag.

    Try:

    <?php
    	$menu = wp_nav_menu(
    	array( 'theme_location' => 'primary-menu', 'container' => '', 'echo' => false ));
    	$menu = str_replace("Our", "<span class='our'>Our</span>", $menu);
    	echo $menu
    ?>

    Thread Starter daledude

    (@daledude)

    Ha, yep. I figured that out about 5 minutes after I posted this… unfortunately my post seemed to disappear from the site, and when I did find it, I was unable to delete or edit it. Thanks for the help.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Use str_replace to replace words in wp_nav_menu output?’ is closed to new replies.