自定义字段未保存 [英] Custom field not saved

查看:121
本文介绍了自定义字段未保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过使用WPGraphQL向用户添加自定义用户字段.因此,我尝试在WPGraphQL官方文档 https中重新创建该示例.://docs.wpgraphql.com/extending/fields/#register-fields-to-the-schema :

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

我已经将类型从 \ WPGraphQL \ Types :: list_of(\ WPGraphQL \ Types :: string())更改为 ['list_of'=>字符串"] .

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

如果我现在执行updateUser突变,则我的兴趣爱好不会得到更新.我在干什么错?

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

突变:

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

输出:

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

推荐答案

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

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

这篇关于自定义字段未保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆