Custom field not saved

感情迁移 提交于 2021-01-29 07:34:45

问题


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": []
      }
    }
  }
}

回答1:


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']);
  }
}


来源:https://stackoverflow.com/questions/63582514/custom-field-not-saved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!