Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jasonbahl/2277835cf5080564dde82cc453cd549b to your computer and use it in GitHub Desktop.
Save jasonbahl/2277835cf5080564dde82cc453cd549b to your computer and use it in GitHub Desktop.
Example showing a connection from one Post Type to another, resolving with related IDs stored in Post Meta
add_action( 'init', function() {
register_post_type( 'physician', [
'hierarchical' => false,
'label' => __( 'Physicians', 'wp-graphql' ),
'public' => true,
'show_in_graphql' => true,
'graphql_single_name' => 'Physician',
'graphql_plural_name' => 'Physicians',
] );
register_post_type( 'disease', [
'hierarchical' => false,
'public' => true,
'label' => __( 'Diseases', 'wp-graphql' ),
'show_in_graphql' => true,
'graphql_single_name' => 'Disease',
'graphql_plural_name' => 'Diseases',
] );
} );
add_action( 'graphql_register_types', function() {
register_graphql_connection( [
'fromType' => 'Physician',
'toType' => 'Disease',
'fromFieldName' => 'diseases',
'resolveNode' => function( $id, $args, $context, $info ) {
return \WPGraphQL\Data\DataSource::resolve_post_object( $id, $context );
},
'resolve' => function( \WPGraphQL\Model\Post $source, $args, $context, $info ) {
$diseases = get_post_meta( $source->ID, '_pods_disease', true );
if ( empty( $diseases ) || ! is_array( $diseases ) ) {
return null;
}
$resolver = new \WPGraphQL\Data\Connection\PostObjectConnectionResolver( $source, $args, $context, $info, 'disease' );
$resolver->setQueryArg( 'post__in', array_values( $diseases ) );
$resolver->setQueryArg( 'post_parent', null );
$connection = $resolver->get_connection();
return $connection;
}
] );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment