One of WordPress’ greatest strengths, at least in my opinion, is its ability to function as a general-purpose content management system. This is usually done through custom post types and custom meta fields. Putting them onto the website is as easy as adding a few pages to your theme.
But what about making a headless WordPress site with GraphQL? How do you add your custom post types and custom meta fields to the GraphQL API?
It’s worth noting that our plugin for creating custom post types, Custom Post Type UI, now does this automatically! But if you’re not using a plugin to create your custom post types, read on to see the code behind the scenes.
I ran into this issue working on a personal website and using the WP GraphQL plugin. This website would be for my music, so I need a custom post type called “Album.”
There are three extra arguments being passed to the register_post_type
function: show_in_graphql
, graphql_single_name
, and graphql_plural_name
. The first enables the custom post type to be added to the GraphQL API, and the last two give the name for the object:
That takes care of our custom post type! But what about the custom meta field?
This code is a little more complicated, so we’ll step through it:
- We hook into the
graphql_register_types
action. This will make sure that our next code is called at the right time. - We call the
register_graphql_field
field with:- The name of the object we are creating the field on (“Album”)
- The name of the field we are creating (
externalLinks
) - Extra arguments for the function
- The extra arguments include a callback function that returns the value of the field.
For our callback function, we’re cheating a little bit. The meta field, find_links
, can have multiple values. The purist approach would be to create a new GraphQL object and allow the links to be individually queryable. The pragmatic approach is to instead make our GraphQL field a String
and encode the full meta field into a JSON object.
The end result here is that we get the data out of WordPress and into our Next.js frontend where we can use it.
You can see the full Next.js source code for my website on GitHub.
With a few tricks, it’s not hard to get the full power of WordPress into your Headless WordPress site. Using a decoupled frontend like Next.js means that the final website can be as complicated or as simple as it needs to be. And when it comes time to update or make new content, it’s as easy as… well, as easy as WordPress.
Want to see what we can do for you? Get in touch!