Last active
September 27, 2022 22:09
-
-
Save jasonbahl/5eee937612e9843066b6177afe29603d 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_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