How to add a field in WPGraphQL extension

Problem

You followed my tutorial on how to create a WPGraphQL Extension . But you want it to be useful. You need to add one (or more) fields to it.

Steps

  1. Find out where you data is

2. Add code to retrieve and fill the field

Find out where you data is

It is up to you to understand WordPress good enough to find the data that you required. Most likely it´s in post or post_meta.

For the sake of this article I assume that you want to expose some of the meta data (which is normally not available) as a field on the Post.

Let´s say the key of the meta field you need is “frank”.

Add code to retrieve and fill the field

You need to tell WordPress with your code what you want your extension to do. For this we need to add an action, which extends the available GraphQL Schema.

To do that add the following code:

add_action( ‘graphql_register_types’, ‘example_extend_wpgraphql_schema’ );

function example_extend_wpgraphql_schema() {
register_graphql_field( ‘Post’, ‘myField’, [
‘type’ => ‘String’,
‘description’ => __( ‘The name of the original source’, ‘wp_graphql’ ),
‘resolve’ => function( $post ) {
$myValue = get_post_meta( $post->ID, ‘frank’, true );
return $myValue;
}
] );}

add_action( ‘graphql_register_types’, ‘example_extend_wpgraphql_schema’ ); tells WordPress that it should call example_extend_wpgraphql_schema when graphql_register_types is called.

Then you add the function example_extend_wpgraphql_schema, which handles the actual work.

The function example_extend_wpgraphql_schema executes register_graphql_field, which registers the field you want. For your first try I suggest copy and paste the code.

This registers a field myField on the Post, which you can query e.g. via the GraphQLi inside your WordPress environment.

You need to also add a so called resolver function (“resolve”). Here it retrieves a post_meta entry for this post and the meta key of “frank”.

Well, that´s basically it. You retrieved the value and added it as a separate field onto the Post Model.

Let me know when it helped you.

Best,

Frank

Sources:

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

Leave a Reply