简体   繁体   中英

Wordpress - customized wp_nav_menu for specific menu

I have a menu named "header-menu" and I only want this menu to be affected by the function I wrote below. How can I prevent other menu's to be affected?

The script is being called like this in header.php

<?php
wp_nav_menu(array('theme_location' => 'header-menu'); 
?>

in functions.php I want this filter to be aware when it is handeling 'header-menu'

<?php
add_filter( 'wp_nav_menu_objects', 'my_menu_filter' );
function my_menu_filter( $items ) {
    $i = 0;
    foreach ( $items as $item )
    {
        if($i == 6)
            $item->title = '<div id="end">.$item->title.</div>';
        else
            $item->title = '<div class="link">.$item->title.'</div>';
        $i++;
    }
    return $items;
}
?>

Found the answer to my own question:

add_filter( 'wp_nav_menu_objects', 'my_menu_filter', 10, 2);
function my_menu_filter( $items, $args ) {
    if($args->theme_location == "header-menu")
    {
        $i = 0;
        foreach ( $items as $item )
        {
            if($i == 6)
                $item->title = '<div id="end">' . $item->title . '</div>';
            else
                $item->title = '<div class="link">' .$item->title.'</div>';
            $i++;
        }
    }
    return $items;
}

The answer was the 4th argument of add_filter which allows a 2nd objects to be passed. To check against conditional statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM