Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wanna preview all the fields that the nav menu $item array holds. Is there a function to fetch it from anywhere and place it inside var_dump?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

The items are set up in wp_nav_menu(). There is a useful filter you can use: 'wp_nav_menu_objects'. It offers the items as $sorted_menu_items and the arguments of the wp_nav_menu() call as $args.

From wp-includes/nav-menu-template.php::wp_nav_menu():

$sorted_menu_items = apply_filters( 'wp_nav_menu_objects', $sorted_menu_items, $args );

So …

  • hook into this filter,
  • store the data somewhere,
  • return the $sorted_menu_items unchanged and
  • print the collected data after all menus are done.

In my following example I print the data on 'shutdown' – that’s the latest hook WordPress fires.

<?php # -*- coding: utf-8 -*-
/**
 * Plugin Name: T5 Collect Nav Menu Items
 * Description: Appends debug information about currently processed nav menu items to pages.
 */

add_filter( 'wp_nav_menu_objects', array ( 'T5_Nav_Menu_Collector', 'collect' ), 99, 2 );

class T5_Nav_Menu_Collector
{
    /**
     * Stores the data
     * @type array
     */
    protected static $collection = array ();

    /**
     * Collect nav menu data.
     *
     * @wp-hook wp_nav_menu_objects
     * @param   array $sorted_menu_items
     * @param   array $args
     * @return  array $sorted_menu_items   Not changed.
     */
    public static function collect( $sorted_menu_items, $args )
    {
        // Since we *know* we have data, we register the print action.
        add_action( 'shutdown', array ( __CLASS__, 'print_collection' ) );

        self::$collection[] = array(
            'args'  => $args,
            'items' => $sorted_menu_items
        );
        return $sorted_menu_items;
    }

    /**
     * Dump the collected data.
     *
     * @wp-hook shutdown
     * @return  void
     */
    public static function print_collection()
    {
        $output = htmlspecialchars( print_r( self::$collection, TRUE ) );
        print "<pre><b>Nav Menu Data</b>\n\n$output</pre>";
    }
}

If there is no nav menu – nothing happens. But if we could collect some data, we get a nice long list at the end of a document with all item properties we can use in other filters.

share|improve this answer
2  
Once again Toscho saves the day. Thanks man!!!!!! –  daniel.tosaba Mar 22 '12 at 6:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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