Created
September 27, 2022 22:13
-
-
Save jasonbahl/ad844ab8437bb73ce501dc9c17241974 to your computer and use it in GitHub Desktop.
This file contains 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( 'graphql_register_types', function() { | |
register_graphql_interface_type( 'Food', [ | |
'description' => __( 'An item of food for sale', 'your-textdomain' ), | |
'interfaces' => [ 'Node', 'NodeWithTitle' ], | |
'fields' => [ | |
'price' => [ | |
'type' => 'String', | |
'description' => __( 'The cost of the food item', 'your-textdomain' ), | |
'resolve' => function( $food ) { | |
return get_post_meta( $food->databaseId, 'price', true ); | |
}, | |
], | |
], | |
'resolveType' => function( $node ) { | |
// use the post_type to determine what GraphQL Type should be returned. Default to Cake | |
return get_post_type_object( $node->post_type )->graphql_single_name ?: 'Cake'; | |
} | |
]); | |
register_graphql_connection([ | |
'fromType' => 'RootQuery', | |
'toType' => 'Food', | |
'fromFieldName' => 'allFood', | |
'resolve' => function( $root, $args, $context, $info ) { | |
$resolver = new \WPGraphQL\Data\Connection\PostObjectConnectionResolver( $root, $args, $context, $info ); | |
$resolver->set_query_arg( 'post_type', [ 'pizza', 'cake' ] ); | |
return $resolver->get_connection(); | |
} | |
]); | |
}); | |
add_action( 'init', function() { | |
register_post_type( 'pizza', [ | |
'public' => true, | |
'label' => 'Pizza', | |
'show_in_graphql' => true, | |
'supports' => [ 'title', 'editor', 'custom-fields' ], | |
'graphql_single_name' => 'Pizza', | |
'graphql_plural_name' => 'Pizza', | |
'graphql_interfaces' => [ 'Food' ], | |
'graphql_fields' => [ | |
'toppings' => [ | |
'type' => [ 'list_of' => 'String' ], | |
'resolve' => function( $pizza ) { | |
$toppings = get_post_meta( $pizza->databaseId, 'topping', false ); | |
return is_array( $toppings ) ? $toppings : null; | |
} | |
], | |
], | |
] ); | |
register_post_type( 'cake', [ | |
'public' => true, | |
'label' => 'Cake', | |
'show_in_graphql' => true, | |
'supports' => [ 'title', 'editor', 'custom-fields' ], | |
'graphql_single_name' => 'Cake', | |
'graphql_plural_name' => 'Cakes', | |
'graphql_interfaces' => [ 'Food' ], | |
'graphql_fields' => [ | |
'frostingColor' => [ | |
'type' => 'String', | |
'resolve' => function( $cake ) { | |
return get_post_meta( $cake->databaseId, 'frosting_color', true ); | |
} | |
], | |
] | |
] ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is snippet shows how to register 2 post types "Pizza" and "Cake" and have them "show_in_graphql". Then, register a connection to query
allFood
, allowing for a single query to return a list of Pizza and Cake together.You can read more about this, at length on the WPGraphQL Blog.