Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
?>
like image 872
user3160134 Avatar asked Jul 06 '14 05:07

user3160134


1 Answers

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.

like image 141
user3160134 Avatar answered Oct 05 '22 23:10

user3160134