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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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_itemsunchanged 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>nn$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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0