Skip to content

Instantly share code, notes, and snippets.

@jasonbahl
Last active September 27, 2022 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonbahl/5eee937612e9843066b6177afe29603d to your computer and use it in GitHub Desktop.
Save jasonbahl/5eee937612e9843066b6177afe29603d to your computer and use it in GitHub Desktop.
add_action( 'graphql_register_types', function() {
register_graphql_field( 'Food', 'price', [
'type' => 'String',
'description' => __( 'The cost of the food item', 'your-textdomain' ),
'resolve' => function( $food ) {
return get_post_meta( $food->databaseId, 'price', true );
}
]);
register_graphql_object_type( 'Pizza', [
'description' => __( 'A tasty food best prepared in an air-fryer', 'your-textdomain' ),
'interfaces' => [ 'Food' ],
'model' => WPGraphQL\Model\Post::class,
'eagerlyLoadType' => true,
'fields' => [
'toppings' => [
'type' => [ 'list_of' => 'String' ],
'resolve' => function( $pizza ) {
$toppings = get_post_meta( $pizza->databaseId, 'topping', false );
return is_array( $toppings ) ? $toppings : null;
}
],
],
]);
register_graphql_object_type( 'Cake', [
'description' => __( 'A tasty dessert, most likely also good if heated in an air-fryer', 'your-textdomain' ),
'interfaces' => [ 'Food' ],
'eagerlyLoadType' => true,
'model' => WPGraphQL\Model\Post::class,
'fields' => [
'frostingColor' => [
'type' => 'String',
'resolve' => function( $cake ) {
return get_post_meta( $cake->databaseId, 'frosting_color', true );
}
],
]
]);
});
add_action( 'init', function() {
register_post_type( 'food', [
'public' => true,
'label' => 'Food',
'show_in_graphql' => true,
'supports' => [ 'title', 'editor', 'custom-fields' ],
'graphql_single_name' => 'Food',
'graphql_plural_name' => 'Food',
'graphql_kind' => 'interface',
'graphql_resolve_type' => function( $food ) {
$food_type = get_post_meta( $food->databaseId, 'food_type', true );
if ( 'pizza' === $food_type ) {
$return_type = 'Pizza';
} else {
$return_type = 'Cake';
}
return $return_type;
},
] );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment