1

I need to hide certain nav items from the menu (based on the password protection functionality) and I'm having trouble getting my custom Walker to work. In fact, I can't even get the standard Walker_Nav_Menu to work when I add it via a filter.

I've created a plugin as follows:

<?php
function myplugin_page_menu_args( $args ) {
    $args['walker'] = new Walker_Nav_Menu;
    return $args;
}

add_filter( 'wp_page_menu_args', 'myplugin_page_menu_args' );
?>

There's no other code in the plugin file, just those 6 lines. I've added this plugin to a brand new install of WordPress (http://dev.matt-howe.co.uk/wordpress/) and the menu rendering is completely broken - all the items are on the same level, and none of them have any text. The right number of <li> elements are generated, and the ids are correct, but the rest is wrong.

I've tried using a custom class with a .walk() method, as so:

class myplugin_walker {
    function walk ( $elements, $to_depth ) {
        return 'test';
    }
}

function myplugin_page_menu_args( $args ) {
    $args['walker'] = new myplugin_walker;
    return $args;
}

add_filter( 'wp_page_menu_args', 'myplugin_page_menu_args' );

This works exactly as expected - the menu renders as 'test'. But trying to use either my own class which extends Walker_Nav_Menu, or the core Walker_Nav_Menu class itself, results in a flat list of empty <li> tags.

I've tried a few other ways to achieve the same result - I've tried adding filters for wp_nav_menu_objects and wp_get_nav_menu_items but neither of my functions seem to get called at all.

Am I barking up the wrong tree here - is this something that won't work as part of a plugin, and needs to be elsewhere in the code? Or am I just missing something obvious?

1 Answer 1

1

Old Q, but I'll give my 2 cents.

  1. The walker class should inherit Walker_Page, not Walker_Nav_Menu as is usually the case with guides on the 'net.
  2. The $item object is a Post Object, containing post_title and ID. To output the URL, you need to call get_permalink($item-ID). Regarding $item->url, it will be unset.
  3. Both theme_location and fallback_cb need to be non-present in the $args array given to wp_nav_menu.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.