-
Notifications
You must be signed in to change notification settings - Fork 0
Menus
Catalyst WP provides an easy to use interface for creating, editing, and using WordPress menus within our theme by building upon the default menu capabilities.
The Atom theme comes with 3 default menus registered, Primary Nav, Auxiliary Nav, and Footer Nav. The settings for these are located in config/navigation.php
.
Nucleus provides a base class for accessing and editing menus within our theme, CatalystWP\Nucleus\models\Menu;
.
This class creates a new Menu
object with 2 properties:
-
links
An array of link data with nested child menus. The key value for each item in the array is that item's nav_menu_item post ID, which we can use to access additional information about that item. -
wp_menu
The original WP_Term object
Each item in the links array has the following properties:
-
link
URL for that item -
title
Menu item label -
slug
Unique slug value -
parent
Set totrue
if this menu item has a child submenu -
child_menu
Nested array of menu items -
child
Set totrue
if this menu item is part of a submenu -
classes
An optional array of CSS class names as specified in the admin
The default header model at models/Header.php
makes use of the menu class and retrieves an instance of the "primary" menu. The only argument it takes is a string specifying the name of the menu as it appears under Appearance > Menus.
$this->menu = new Menu('Primary');
We can then use the menu within our template as follows. You can see this example from templates/molecules/menu.handlebars
:
{{#if menu}}
{{#with menu}}
<div class="menu molecule">
<div class="nav">
<ul>
{{#each links}}
<li>
{{> atoms/menu-item}}
{{#if parent}}
<ul class="submenu">
{{#each child_menu}}
<li>
{{> atoms/menu-item}}
</li>
{{/each}}
</ul>
{{/if}}
</li>
{{/each}}
</ul>
</div>
</div>
{{/with}}
{{/if}}
Each individual menu item is considered an atom, found in templates/atoms/menu-item.handlebars
:
<a href="{{link}}" title="{{title}}" class="{{#if parent}}has-submenu{{/if}}">{{title}}</a>
The Menu
class provides an updateMenuItems
method that allows us to iterate over all items in a menu and add or modify data using a callback function instead of a custom walker.
$this->menu->updateMenuItems(function($value, $key) {
$value['foo'] = 'bar';
return $value;
});
This would add the key of foo
with a value of bar
to every item in the menu.
Note: This anonymous callback essentially serves as an array_map function, so we must return $value.