Skip to content

Instantly share code, notes, and snippets.

@jasonbahl
Created February 6, 2019 19:19
Show Gist options
  • Save jasonbahl/0e77959bb91d501e439a98b85458dd5d to your computer and use it in GitHub Desktop.
Save jasonbahl/0e77959bb91d501e439a98b85458dd5d to your computer and use it in GitHub Desktop.
Add custom fields to User Mutations in WPGraphQL
add_action( 'graphql_register_types', function() {
$args = [
'type' => 'String',
'description' => __( 'Custom field for user mutations', 'your-textdomain' ),
'resolve' => function( \WP_User $user ) {
return get_user_meta( $user->ID, 'custom_field_meta_key', true );
}
];
register_graphql_field( 'User', 'customField', $args );
register_graphql_field( 'CreateUserInput', 'customField', $args );
register_graphql_field( 'UpdateUserInput', 'customField', $args );
} );
add_action( 'graphql_user_object_mutation_update_additional_data', function( $user_id, $input, $mutation_name, $context, $info ) {
if ( ! empty( $input['customField'] ) ) {
// Consider other sanitization if necessary and validation such as which
// user role/capability should be able to insert this value, etc.
$value = sanitize_text_field( $input['customField'] );
update_user_meta( $user_id, 'custom_field_meta_key', $value );
}
}, 10, 5 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment