Create Gatsby navigation from WordPress menus

Jason Lengstorf
InstructorJason Lengstorf
Share this video with your friends

Social Share Links

Send Tweet

WordPress supports custom menus, and we can use those to control navigation on Gatsby sites. In this video, we’ll read a menu from WordPress, replace absolute links with relative versions, and generate the main navigation for our Gatsby site.

Jason Lengstorf: [00:00] If we want to use menus defined in WordPress as our navigation in Gatsby, we need to load those via GraphQL.

[00:08] Inside the wpgraphql query we're going to get menus, nodes, and then we want to load the id and the name for each menu. This will show us our Main Menu and what the id for that menu is.

[00:22] Next, we're going to load that menu, so let's go to a query, wpgraphql and menu. We want the id of this. Inside of it, we can get the menuItems. Each menu item is going to have nodes. Then we want to get the url and the label, which will give us where it links to and the about. We also want to get the id so that we can uniquely identify it inside of React.

[00:57] Once we know how to load these items, we can grab just this chunk, because we're going to modify the layout query here. Inside, next to the general settings, we're going to query for the menu. This is hardcoded. We could do this through context or a bunch of other ways, but for this example, we're going to keep it simple and hardcode it right in there.

[01:18] What we really need is the menu item. We're going to create a new constant called items, and then dig into this data object, so data.wpgraphql.menu.menuItems, and the nodes are what we really need here. Then, inside of our header just after the home link, we will map through items. For each menu item, we're going to return a Link, and that is going to link to the item.url.

[01:50] We're going to give it a key for React of item.id, and inside, we will give it item.label so that we know what we're clicking on. If we save this and head back out, we can see now that it is linking to the About and the Blog.

[02:03] The problem is, the link is broken. It's trying to link to the full WordPress URL. This is something that WordPress does to try to make sure that links are always safe, but we need to change that behavior.

[02:17] Fortunately, we get the WordPress URL from general settings, so we can grab that right out. Then in our nodes, we can just map over each node. In here, we'll return the whole item, but we're going to rewrite the URL to be item.url and we'll replace this URL here with nothing. Once we've done that, we can see that now our links work.