自定义字段未保存

时间:2020-08-25 15:44:17

标签: wordpress graphql headless-cms wp-graphql

我尝试通过使用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": []
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

感谢xadm,我唯一忘记的是真正改变了这个领域。我对文件有点困惑,我的错。 (我真的是WPGraphQL btw的新手)

这是必须添加的内容:

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