Homepage
Link to WPGraphQL on Github
Link to WPGraphQL on WordPress.org

register_graphql_field

Add a field to a Type in the GraphQL Schema

Parameters

  • $type_name (string): The name of the GraphQL Type in the Schema to register the field to
  • $field_name (string): The name of the field. Should be unique to the Type the field is being registered to.
  • $config (array): Configuration for the field
    • $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' ]
    • $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.

Source

File: access-functions.php

Examples

Below are some examples of using the function to extend the GraphQL Schema.

Register a Root Field

This example adds a field to the root of the GraphQL Schema.

Example Query

Screenshot of the example query for testField
Screenshot of the example query for testField

Register a Post Field

This example shows how to register a field to the Post type.

Example Query

Screenshot of an example query for the "testPostField" registered to the "Post" Type
Screenshot of an example query for the “testPostField” registered to the “Post” Type

Register a field to an Interface

This example shows how to register a field to an Interface. In this example, a field is registered to the “ContentNode” Interface. This means any Type (any WordPress Post Type) in the Schema that implements the “ContentNode” interface will have the field.

Example Query:

Screenshot of a query for contentNodes of multiple content types asking for the "testContentNodeField" field
Screenshot of a query for contentNodes of multiple content types asking for the “testContentNodeField” field