How to add or expose a custom PostType in WPGraphQL extension

Problem

You followed my tutorial on how to create a WPGraphQL Extension . But you want it to be useful. You want to query a custom post type.

Steps

  1. Find out your post type
  2. Add code to add a PostType to your GraphQL Schema
  3. Add code to expose a PostType to your GraphQL Schema

Find out your post type

Finding your post type is easy. Just search for a post that has the required type in the WordPress posts table and copy it.

Add code to add a PostType to your GraphQL Schema

I will show you how to add a PostType. For the sake of the Article lets call it Hannibal.

To register “Hannibal” as a PostType, copy the following code:

register_post_type( ‘hannibal’, [
‘show_ui’ => true,
‘labels’ => [
//@see https://developer.wordpress.org/themes/functionality/internationalization/
‘menu_name’ => __( ‘Hannibal’, ‘your-textdomain’ ),
],
‘show_in_graphql’ => true,
‘hierarchical’ => true,
‘graphql_single_name’ => ‘hannibal’,
‘graphql_plural_name’ => ‘hannibal’,
] );

The first parameter to register_post_type is the way the post type is saved inside that database.

“graphql_single_name” contains the name to use for one Entry of the to be registered Type.

Analog “graphql_plural_name” contains the name for multiple entries.

That´s it. Look at your GraphQLi Explorer or try it externally to see that now you can query one “Hannibal” or get a list of Hannibals.

Add code to expose a PostType to your GraphQL Schema

If a 3rd party tool has registered the Type already, but didn´t expose it to your GraphQL Schema (because it doesn´t know WPGraphQL), you need to do something slightly different to just expose it:

add_filter( ‘register_post_type_args’, function ($args, $post_type) {

if ( ‘hannibal’ ==== $post_type) {

$args[‘show_in_graphql’] = true;

$args[‘graphql_single_name’] = ‘hannibal’;
$args[‘graphql_plural_name’] = ‘hannibal’;

}

return $args;

}, 10, 2 );

As you can see, it´s not completly different but a bit. You´re basically interfere with the registration and make the type known to GraphQL.

Let me know when this helped you.

Best,

Frank

Sources:

https://www.wpgraphql.com/docs/custom-post-types/

https://www.wpgraphql.com/docs/build-your-first-wpgraphql-extension/

Leave a Reply