WordPress.org

Ready to get started?Download WordPress

Forums

Use str_replace to replace words in wp_nav_menu output? (3 posts)

  1. daledude
    Member
    Posted 2 years ago #

    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...)

  2. Jon Hall Design
    Member
    Posted 2 years ago #

    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
    ?>
  3. daledude
    Member
    Posted 2 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic