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

register_graphql_union_type

Given a Type Name and a `$config` array, this adds an UnionType to the TypeRegistry

Parameters

  • $type_name (string): The unique name of the Type in the Schema. This must be unique amongst the entire Schema.
  • $config (array): Configuration for the field
    • $description (string): Description of the Union type.
    • $types (array): An array of Types that the union could return
    • $resolveType (function): A function that takes the resolving data and determines what GraphQL Type should be returned.

Source

File: access-functions.php

Example

Unions are useful when a field needs to return different Types that don’t implement a common interface.

An example of when using a Union might be good would be adding search functionality that could search across. For example, if you had a Movie Database site, you might want to have a search query return Genres (a custom taxonomy for example sake) or Movies (a custom post type for example sake) in the same list.

To do this, you would need to register a Union that could return a `Genre` or a `Movie`.

We’re going to assume that we already have a Genre Taxonomy registered to show in GraphQL, and a Movie Post Type registered to Show in GraphQL, so we can make use of the Genre and Movie Types in our Schema.

Below, is a snippet showing how to register a Union that could return a Genre or a Movie.

This registers a Union type named GenreOrMovieUnion.

The typeNames field defines what Types from the Schema are possible to be returned. In this case, the Genre or Movie Type.

Then resolveType is the function that runs during execution to determine what Type should be returned. It accepts the resolving data, and you can use that data to determine what Type to return.

In our case, either a Post or Term would be returned to the Union, so we can check which Type it is and determine whether it’s a Taxonomy or a Post and set the return type appropriately.

Now, we can use the Union in a field.

Now we have a searchMoviesAndGenres field on our RootQuery that returns a list of items, containing both Posts and Terms, we could now search like so:

Now, we can query like so:

And we’ll receive the following data: