register_graphql_fields
Add one or more fields to a Type in the GraphQL Schema
register_graphql_fields( string $type_name, array $fields );
Parameters
- $fields (array): Associative array of key/value pairs where the key is the name of the field and the value is a config array for the field.
- $name (string): The name of the field to add to the Type. “camelCase” recommended.
- $config (array): The config for the field being registered
- $type (string | array): The name of the GraphQL Type the field will return. The resolve function must return this type.
- For non-null fields:
'type' => [ 'non_null' => 'TypeName' ]
- For listOf fields:
'type' => [ 'list_of' => 'TypeName' ]
- For non-null fields:
- $description (string): Description of the field. This will be used to self-document the schema and should describe to clients how the field should be used.
- $resolve (function): Function that will execute when the field is asked for in a query.
- $type (string | array): The name of the GraphQL Type the field will return. The resolve function must return this type.
Source
File: access-functions.php
Examples
Below are some examples of using the function to extend the GraphQL Schema.
Register Root Fields
This example adds multiple fields to the root of the GraphQL Schema.
add_action( 'graphql_register_types', function() {
register_graphql_fields( 'RootQuery', [
'fieldOne' => [
'type' => 'String',
'description' => __( 'Example field added to the RootQuery Type', 'replace-with-your-textdomain' ),
'resolve' => function( $root, $args, $context, $info ) {
return 'Field one value...';
}
],
'fieldTwo' => [
'type' => 'Boolean',
'description' => __( 'Another example field added to the RootQuery Type', 'replace-with-your-textdomain' ),
'resolve' => function( $root, $args, $context, $info ) {
return 2;
}
],
]);
});
Example Query:
{
fieldOne
fieldTwo
}
Register Post Fields
This example shows how to register fields to the “Post” type.
add_action( 'graphql_register_types', function() {
register_graphql_fields( 'Post', [
'testFieldOne' => [
'type' => 'String',
'description' => __( 'Example string field added to the Post Type', 'replace-with-your-textdomain' ),
'resolve' => function( \WPGraphQL\Model\Post $post, $args, $context, $info ) {
return 'Example string with the title of the post: ' . $post->titleRendered;
}
],
'testFieldTwo' => [
'type' => 'Boolean',
'description' => __( 'Example boolean field added to the Post Type', 'replace-with-your-textdomain' ),
'resolve' => function() {
return false;
}
]
] );
} );
Example Query
{
posts(first: 1) {
nodes {
title
testFieldOne
testFieldTwo
}
}
}