3

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?

0

1 Answer 1

5

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.

0

Your Answer

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

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