1. 13
    Add a Custom Post Type to the GraphQL Headless WordPress API Endpoint
    1m 40s

Add a Custom Post Type to the GraphQL Headless WordPress API Endpoint

Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

In this lesson, we will expose a Custom Post Type to the graphQL layer. This would normally be done in the Custom Post Type Plugin UI but if you browse the options you'll notice that there is no setting for GraphQL. This means we will need to write a custom function that exposes our user-created post type.

We will use add_filter in our headless.php file to expose the chairs post type. The filter we'll use is register_post_type_args. There are three fields that need to explicitly declared: show_in_graphql, graphql_single_name, graphql_plural_name.

Instructor: [0:00] If we look at the GraphQL schema, as we can explore in the Graphical IDE, you'll notice that we have pages and pages, posts and posts, but we don't have our custom post of chairs. When we create a code custom post using the custom post type UI, we'll see that there are lots of fields here.

[0:17] One of them is to show in the REST API, and that set to true. In order for us to show this post type in the GraphQL schema, we need to set the show and GraphQL variable to be true, which is not in the Settings menu. We're going to add some custom code to our headless function file.

[0:35] Previously, in my functions.php file, right at the bottom, I'm requiring my lib/headless-php file. This is where I'm going to add my custom code. We're going to add a filter, and the filter we're going to add is going to occur when they're registering the post type arguments. We'll take a callback function, which takes two arguments, the arguments and the post type.

[0:58] We want to test, is the post type equal chairs? If it is, we want to add to the arguments.

[1:03] The first thing we want to do is we want to show in GraphQL and that one's equal true. The second thing we need to provide is a specific GraphQL single name. It's going to be chair, and a specific GraphQL plural name chairs.

[1:17] We'll then return those arguments and we need to provide two extra arguments here. First, the priority. We're going to put 10, it's in the middle. The last argument we need to give is how many arguments are callback function takes? In this case, it's two.

[1:30] Don't forget our semi-colon. We go back over to our RDA and refresh. After a few seconds, our schema will appear. Now, we have our chairs and our chairs, chairs, nodes, title as it appears.