Setup WordPress with GraphQL

29 January 2022

In the first few posts looking at Next.js we’ve been focusing on the layout and structure of the pages and building the header, main body and footer. Now we’ve got a simple template set up, we can start populating pages with content.

There are many options for where we store our content including markup files for our project and many options in terms of Content Management Systems. In the past, the majority of the websites I’ve worked on have been built on WordPress so I chose to use that as my CMS as that’s what I’m most comfortable and familiar with.

We’re going to set up WordPress as a headless CMS to hold all our pages, blog posts, menus and images. To access all this from WordPress we’re going to use GraphQL which is a query language for API’s. This allows us to easily retrieve all the data we need from WordPress to populate our Next.js project with content at the time our app is built.

Installing WPGraphQL

To get set up with GraphQL on WordPress we’ll install the WPGraphQL plugin which provides all the functionality we need to use GraphQL on a WordPress site.

Once installed you’ll have a GraphQL item in the WordPress menu which will allow you to change the settings of the plugin and access the GraphiQL IDE to build and test queries.

Using WPGraphQL

In the GraphiQL IDE copy and paste the following into the centre query window of the GraphiQL interface and click the play button at the top. This will execute the query.

{
  pages {
    edges {
      node {
        id
        title
        content
        slug
      }
    }
  }
}

If it’s configured correctly you should see the data from all the pages on your WordPress site in JSON format.

Using GraphQL we can not only ask for all our pages, but also all our posts in one query.

{
  posts {
    edges {
      node {
        title
        content
        date
      }
    }
  }
}

One of the biggest advantages of using GraphQL is the amount of data we can retrieve in just one request. In one request we receive data for every page or post on our site, whether there were 10 or 1000.

We can take advantage of this in NextJS by requesting this data and using it to automatically build dynamic routes for each page or post. And that’s what we’ll look at next.

In the meantime, have a look at the WPGraphQL documentation to see what other data you are able to retrieve from WordPress.