Use WordPress Custom Post Types And Taxonomies with GraphQL
By default in custom post types, taxonomies and any custom post meta aren’t available in GraphQL. We have to tell WordPress which bits of data we want to be exposed to GraphQL so that we can retrieve it in a query.
This can be done when any of these content types are registered, but if they are created by a plugin or provided with a theme that code might not be straight forward to find.
Custom Post Types
To display a custom post type to GraphQL we can edit the post type arguments. WordPress provides us with a filter to do that. The example below should be added to the functions.php
file in your theme or child theme.
Using the register_post_type_args
filter, we call a function which finds our custom post type which in this example is called ‘portfolio’. The arguments for this post type are edited to enable the show_in_graphql
option and we pass in the name for a single and plural GraphQL entry.
Now we’ve added the arguments to output the custom post type in PHP we can load up the GraphQL IDE and check if the options are there. I’m then able to create a query to return the portfolio custom post type.
{
portfolios {
edges {
node {
title
id
content
date
slug
}
}
}
}
Custom Taxonomy
The process for showing taxonomies in GraphQL is very similar, it just uses the register_taxonomy_args
filter and into the function you enter the taxonomy name. The arguments to modify are the same as the ones modified in the custom post type.
Once the arguments are added the taxonomy will be available to query in GraphQL.
query profile {
profiles {
edges {
node {
name
description
slug
}
}
}
}
Custom Post Fields
To register a custom field associated to our custom post type or taxonomy, we can use the register_graphql_field
function and hook it into the graphql_register_types
action.
Within the register_post_field
function we get a list of GraphQL enabled post types and loop through them until we find our post type called portfolio
.
We can then call the register_graphql_field
function which we pass into the following variables.
$graphql_single_name
– This is the single name we passed to the post type arguments when enabling GraphQL.
$graphql_field_name
– The name of the field you want displayed in the GraphQL query.
$field_config
– An array to configure the GraphQL field which contains the:
- type: Tells GraphQL what type of field this is, in our case a string
- description: The description that appears in GraphQL query
- resolve: What happens when this GraphQL field is queried. In our example we’re passing a function that returns the post meta for the custom field using the
get_post_meta
function.
We’re then able to query and retrieve the value of our custom field.
query MyPortfolioImage {
Portfolio {
edges {
node {
portfolioImage
}
}
}
}
The full documentation for adding Custom Post Types, Custom Taxonomies and Custom Fields can be found on the WPGraphQL website.