wordpressgraphqlheadless-cmswp-graphql

Custom field not saved


I try to add a custom user field to the user by using WPGraphQL. Therefore I tried to recreate the example in the official WPGraphQL documentation https://docs.wpgraphql.com/extending/fields/#register-fields-to-the-schema :

add_action('graphql_init', function () {
  $hobbies = [
    'type'        => ['list_of' => 'String'],
    'description' => __('Custom field for user mutations', 'your-textdomain'),
    'resolve'     => function ($user) {
      $hobbies = get_user_meta($user->userId, 'hobbies', true);
      return !empty($hobbies) ? $hobbies : [];
    },
  ];

  register_graphql_field('User', 'hobbies', $hobbies);
  register_graphql_field('CreateUserInput', 'hobbies', $hobbies);
  register_graphql_field('UpdateUserInput', 'hobbies', $hobbies);
});

I already changed the type from \WPGraphQL\Types::list_of( \WPGraphQL\Types::string() ) to ['list_of' => 'String'].

If I now execute the updateUser mutation my hobbies don't get updated. What am I dowing wrong?

Mutation:

mutation MyMutation {
  __typename
  updateUser(input: {clientMutationId: "tempId", id: "dXNlcjox", hobbies: ["football", "gaming"]}) {
    clientMutationId
    user {
      hobbies
    }
  }
}

Output:

{
  "data": {
    "__typename": "RootMutation",
    "updateUser": {
      "clientMutationId": "tempId",
      "user": {
        "hobbies": []
      }
    }
  }
}

Solution

  • Thanks to xadm, the only thing I forgot was to really mutate the field. I was a bit confused by the documentation, my fault. (I really am new to WPGraphQL btw)

    Here's what has to be added:

    add_action('graphql_user_object_mutation_update_additional_data', 'graphql_register_user_mutation', 10, 5);
    
    function graphql_register_user_mutation($user_id, $input, $mutation_name, $context, $info)
    {
      if (isset($input['hobbies'])) {
        // Consider other sanitization if necessary and validation such as which
        // user role/capability should be able to insert this value, etc.
        update_user_meta($user_id, 'hobbies', $input['hobbies']);
      }
    }