Skip to content

Instantly share code, notes, and snippets.

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/db8f63b50e1c2a10d6147d1540116c2e to your computer and use it in GitHub Desktop.
Save jasonbahl/db8f63b50e1c2a10d6147d1540116c2e to your computer and use it in GitHub Desktop.
// Add Hobbies to GraphQl
add_action('graphql_init', function () {
$hobbies = [
// 'type' => 'String',
'type' => ['list_of' => 'String'],
'description' => __('Custom field for user mutations', 'your-textdomain'),
'resolve' => function ($post) {
$hobbies = get_post_meta($post->ID, 'hobbies', true);
return !empty($hobbies) ? $hobbies : '';
},
];
register_graphql_field('Post', 'hobbies', $hobbies);
register_graphql_field('CreatePostInput', 'hobbies', $hobbies);
register_graphql_field('UpdatePostInput', 'hobbies', $hobbies);
});
// Update Post Meta
add_action( 'graphql_post_object_mutation_update_additional_data', 'graphql_register_edit_mutation', 10, 5 );
function graphql_register_edit_mutation( $post_id, $input, $mutation_name, $context, $info ) {
$sanitized = ! empty( $input['hobbies'] ) ? array_map( static function( $hobby ) {
return sanitize_text_field( $hobby );
}, $input['hobbies'] ) : [];
if ( ! empty( $sanitized ) ) {
update_post_meta( $post_id, 'hobbies', $sanitized );
}
return [ 'value' => $input['hobbies'] ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment