In WordPress, Navigation Menus consist of 2 types of entities: Menus and MenuItems.
- Menu: is the entity that groups MenuItems together.
- MenuItem: The individual items in a Menu. Each MenuItem can be a custom link, or a reference to a connected object such as a Post, Page, Category, Tag, or other entity. MenuItems can have hierarchical relationships with other MenuItems, meaning MenuItems can be nested with parent/child relationships.
NOTE: Menus and Menu Items in WordPress are not viewable by public requests until they are assigned to a Menu Location. WPGraphQL respects this access control right, so if you are not seeing data in your queries for menus and menu items, make sure the menu is assigned to a location.
Below are some examples of querying Menus and Menu Items
Below is an example query for a list of Menus and the Menu Items associated with the menu.
Below is an example of a GraphQL Query for a specific menu using identified by it’s Global ID.
Often, it can be inconvenient to query Menus by ID. Since Menu names in WordPress are unique, the name can be used as a unique identifier and we can query for Menus by name using the
idType argument like so:
Querying a list of Menu Items with no arguments will return Menu Items associated with any Menu.
It’s likely more common that you would want to query Menu Items associated with a specific Menu Location, like so:
One thing you may have noticed is that Menu Items will be returned in a flat-list by default, meaning that hierarchical relationships such as parent, children, grand-child Menu Items, will all be returned together in a flat list.
There’s a good chance you might need to convert a flat list into a hierarchical list in the consumer application to be used in a component such as a Checkbox Tree or Dropdown Menu, for example.
You can see this technique in action in the codebase for the website you’re reading here.
Given the query above, we might have a payload of data like so:
Here we can see that there are some nodes with a null
parentId value, and some that do have a
A function like the following could be used to convert the flat list to a hierarchical list.
This could be used like so:
And the data would be transformed like so:
WPGraphQL does not yet support mutations for menus or menu items.