How to add Active states and icons in wordpress wp

2019-09-06 18:24发布

问题:

function main_nav() { 
    wp_nav_menu( 
        array( 
            'menu' => 'main_nav', 
            'theme_location' => 'main_nav', 
            'container_class' => 'menu clearfix', 
            'link_before'     => '<span>',
            'link_after'      => '</span>',
            'fallback_cb' => 'bones_main_nav_fallback' 
        )
    );
}

I'm trying to use link_before and link_after to append a span tag to the wp_nav_menu so so that I may add an icon to each navigation.

Example:

<li><span><img src="home.gif" /></span><a href="home.php"> Home</a></li>

I am super super new to php and wordpress. Any ideas on how to tackle this?

Secondary question, Adding a css-class to the "current active state" anchor? Just for styling.

回答1:

Perhaps you will need to change this code... but here is example. You can see the Reference to wp_nav_menu and add holder pattern... and later just change it by your local replaments settings (see array before replacements)

function main_nav() { 
    $menu = wp_nav_menu( 
        array( 
            'menu' => 'main_nav', 
            'theme_location' => 'main_nav', 
            'container_class' => 'menu clearfix', 
            'link_before'     => '<span></span>',
            'echo'            => $false,
            'fallback_cb' => 'bones_main_nav_fallback' 
        )
    );

    $patterns = array(
        '<span></span><a href="home.php"',
    );
    $replacements = array(  
        '<span><img src="home.gif" /></span><a href="home"'
    );

    echo str_repalce($patterns, $replacements, $menu); 

}

and btw, list items contain number of current classes so you able to use tham to track current item of your menu too.