Using Shortcodes in WP-Menus in WP 3.1 (via nav_menu_objects)?

I’ve found this new plugin

http://wpsmith.net/wordpress/creating-multiple-custom-menus-in-wordpress-3-1

that is using a new 3.1 hook (wp_nav_menu_objects) to remove specific nav-menu-items from the nav-menu-item array before they are parsed by the walker class, if a user isn’t logged in. The plugin uses a specific CSS-class as identifier to decide which items to remove.

So I’ve been wondering if it couldn’t be possible to use shortcodes in nav-menu-item descriptions, in order to have an advanced set of conditionals with respect to the display of specific menu items (like display on page x, don’t display on page y, or, particularly useful: automatic inclusion of child pages/categories, etc. by inserting them into the nav_menu_item array before the array is parsed by the walker)

But adding

add_filter(‘wp_nav_menu_objects’, ‘do_shortcode’);

is causing the page to not load correctly. Not a blank page error, but the page stops rendering right after the nav menu containter div. Is there any way to use native WP shortcode functionality for this purpose? Or would it be necessary to create a custom shortcode parser within the function analysing the nav-item-contents?

Thanks for any ideas!

3 Answers
3

The problem is that do_shortcode() expects a string in it’s first parameters while wp_nav_menu_objects get’s passed an array of menu objects.

Sou you’d have to write your own wrapper function to do_shortcode, something like this…

function my_nav_menu_objects_shortcode_mangler($items) {
    foreach ($items as $item) {
        $item->classes = explode(' ', do_shortcode(implode(' ', (array)$item->classes)));
    }
    return $items;
}

may work. You’d have to find out about the structure of the nav menu objects ($item) by looking at the source in wp-includes/nav-menu-template.php and then derive which properties best to modify and how (which format they have, how to convert that to a string so you can run a shortcode over it, etc.).

It would appear to me, though, that other means of implementing such logic might be better than hacking shortcode functionality into it.

Also note that using that model you cannot have a shortcode in one property of your menu item and expect it to modify the output of another…like you can’t have a shortcode in your menu item label and hope it adds or removes css classes. Just doesn’t work that way.

Leave a Comment