Convert output of nav_menu items into a tree-like multidimensional array

The problem of building a tree from a flat array has been solved here with this, slightly modified, recursive solution:

 

where we added the prefixed wpse_children attribute to avoid name collision.

Now we only have to define a simple helper function:

 

Now it becomes super easy to transform a navigational menu into it’s tree structure with:

 

For JSON, we can simply use:

For a slightly different version, where we handpicked the attributes, check out the first revision of this answer here.

Update: Walker Class

Here’s a rather sketchy idea how we could try to hook into the recursive part of the the display_element() method of the abstract Walker class.

 

where WPSE_Nav_Menu_Tree is an extension of the Walker_Nav_Menu class:

 

This might give us an alternative approach if it works.

1 سال پیش

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *