1

我尝试使用 WPGraphQL 向用户添加自定义用户字段。因此,我尝试在官方 WPGraphQL 文档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);
});

我已经将类型从 更改\WPGraphQL\Types::list_of( \WPGraphQL\Types::string() )['list_of' => 'String']

如果我现在执行 updateUser 突变,我的爱好不会得到更新。我做错了什么?

突变:

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

输出:

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

1 回答 1

1

感谢xadm,我唯一忘记的就是真正改变这个领域。我对文档有点困惑,我的错。(顺便说一句,我真的是 WPGraphQL 的新手)

以下是必须添加的内容:

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']);
  }
}
于 2020-08-25T21:44:40.053 回答