Created
January 25, 2019 18:46
-
-
Save jasonbahl/3d6a47d692c4eb4207328af8cbfdd689 to your computer and use it in GitHub Desktop.
Showcases how to register custom connections with WPGraphQL. See:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action( 'init', function() { | |
register_post_type( 'audio-track', [ | |
'public' => true, | |
'label' => __( 'Audio Tracks', 'wp-graphql' ), | |
'show_in_graphql' => true, | |
'graphql_single_name' => 'AudioTrack', | |
'graphql_plural_name' => 'AudioTracks' | |
] ); | |
register_post_type( 'audio-playlist', [ | |
'public' => true, | |
'label' => __( 'Audio Playlists', 'wp-graphql' ), | |
'show_in_graphql' => true, | |
'graphql_single_name' => 'AudioPlaylist', | |
'graphql_plural_name' => 'AudioPlaylists' | |
] ); | |
} ); | |
add_action( 'graphql_register_types', function() { | |
add_filter( 'graphql_post_object_connection_query_args', function( array $query_args, $source, array $args, \WPGraphQL\AppContext $context, \GraphQL\Type\Definition\ResolveInfo $info ) { | |
if ( 'RootQueryToAudioUnionConnection' === $info->returnType->name ) { | |
$query_args['post_type'] = [ 'audio-track', 'audio-playlist' ]; | |
}; | |
return $query_args; | |
}, 10, 5 ); | |
register_graphql_union_type( 'AudioUnion', [ | |
'typeNames' => [ 'AudioTrack', 'AudioPlaylist' ], | |
'resolveType' => function( $source ) { | |
$type = null; | |
if ( $source instanceof \WP_Post ) { | |
switch ( $source->post_type ) { | |
case 'audio-playlist': | |
$type = \WPGraphQL\TypeRegistry::get_type( 'AudioPlaylist' ); | |
break; | |
case 'audio-track': | |
default: | |
$type = \WPGraphQL\TypeRegistry::get_type( 'AudioTrack' ); | |
break; | |
} | |
} | |
return $type; | |
} | |
]); | |
register_graphql_connection([ | |
'fromType' => 'RootQuery', | |
'toType' => 'AudioUnion', | |
'fromFieldName' => 'audio', | |
'resolve' => function( $root, $args, $context, $info ) { | |
return \WPGraphQL\Data\DataSource::resolve_post_objects_connection( $root, $args, $context, $info, null ); | |
} | |
]); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment