🧐 How To

Menus

Working with WordPress menus

For simplicities sake, all menus are pre-loaded in the starter theme's views/_app.graphql. It looks something like this:

views/_app.graphql
query CommonData {
  menus {
    nodes {
      menuItems {
        nodes {
          ...MenuItemFields
        }
      }
      locations
      slug
      name
    }
  }
}

fragment MenuItemFields on MenuItem {
  label
  title
  target
  url
  cssClasses
  childItems {
    nodes {
      label
      title
      target
      url
      cssClasses
    }
  }
}

The fragment is used there so that it's easy to grab TypeScript types for the menu data structure.

There's also a backend/menus.php file, which has a call to register_nav_menus function call, which sets up 'menu locations'. If you need more than just one menu, you can add them there.

register_nav_menus([
  'main' => 'Main Menu',
  'footer' => 'Footer Menu'
]);

The starter theme also comes with a components/atoms/Menu.tsx component. It's included as a component which you can tailor to your needs.

To use the menu component, you'll need to specify the menu location which you defined in PHP. Assuming you've got yarn dev running, the menu locations will auto-complete with TypeScript.

<Menu location="Main">

It's recommended that if you need to stylise or customise the Menu, that you kinda keep that file nice and generic, and create a new component which uses the Menu component as a base. (Or alternatively, you can always copy/paste the Menu code into your new component.)

components/atoms/MyCoolMenu.tsx
import { Menu } from "@components/atoms/Menus";

export const MyCoolMenu = styled(Menu, {
  display: "flex",
  li: {
    marginLeft: "20px",
    a: {
      fontFamily: '"Comic Sans"',
    },
  },
});