Put WordPress menu in source

Hi!

I want owners of a site to be able to configure their own menus through WordPress. So I set myself the task to make that happen with the nav.js component of the mars-theme.

Surprisingly WordPress doesn’t expose menus in the REST API. But there’s a plugin for that (https://github.com/nekojira/wp-api-menus), so that problem is fixed, somewhat.

The first step seems to be creating a handler that’s able to retrieve the content of a menu-location (just like a PHP theme would use the menu-location for showing a specific menu on a specific page), so I’m using this endpoint of my installation: https://frontity.noesteprojecten.nl/wp-json/wp-api-menus/v2/menu-locations/menu-1

And this is my handler, which uses the location (now called ‘menu-1’) of the theme for retrieving the content:

// custom handler for menus
const menuHandler = {
  // this is the pattern which will include the name of the menu
  name: "menu",
  pattern: "menu/:menuName",

  func: async ({ route, params, state, libraries }) => {
    const response = await libraries.source.api.get({
      endpoint: `/wp-api-menus/v2/menu-locations/${params.menuName}/`,
    });
    const option = await response.json();

    // add data to 'source'
    const data = state.source.get(route);
    Object.assign(data, { ...option, isMenu: true });
  },
};

Now, I see the data appearing in `state.source.data[‘menu/menu1’] like this:
Schermafbeelding 2020-07-31 om 17.21.14

But I can’t figure out how to really add the data to per example state.source.menus. Maybe it doesn’t even need to be there, but to me that seemed to be the next step into integrating it into the nav.js file of mars-theme. Or is state.source restricted to post-types and taxonomies and am I on the wrong path alltogether?

Whatever the answer to the above question is, I’m unsure how to use the available data to make it work in nav.js now. Any help towards my next step into this ‘quest’ is greatly appreciated!

Hey @dominique,

Did you take a look at this thread?

It looks like this is a common feature, and some people of the community have shared how they’ve accomplished it.

Hi @Pablo,

I didn’t come across that topic, although I’ve read other ones on the Community but those weren’t working out for me so far. I will read the comments in your link as soon as I have time and will let you know if it works for me! Thanks!

1 Like