【问题标题】:Create a new user using WP REST API and declare meta object使用 WP REST API 创建新用户并声明元对象
【发布时间】:2018-01-10 19:44:26
【问题描述】:

我在这里遇到一个问题。我用这个JSON 数据发送POSThttp://localhost/wp-json/v2/wp/users/

{
    "username" : "johndoe",
    "email": "jondoe@gmail.com",
    "password": "qwerty",
    "meta": {
        "icq": "11223344"
    }

}

但是当我去查看结果时,meta 对象是空白的。我使用插件实现了目标,但是这个插件使用cookie 进行身份验证,而我还有另一个插件使用JWT 进行身份验证,所以我认为一个任务需要很多插件。

有人有同样的问题吗?甚至在插件的官方文档中我也没有找到解决方案。

【问题讨论】:

    标签: php json wordpress wordpress-rest-api


    【解决方案1】:

    刚刚在 Stack Overflow 的另一个问题中找到了解决方案。使用函数register_meta()

    register_meta('user', 'icq', array(
      "type" => "string",
      "show_in_rest" => true
    ));
    

    现在我可以使用:

    {
        "username" : "johndoe",
        "email": "jondoe@gmail.com",
        "password": "qwerty",
        "meta": {
            "icq": "11223344"
        }
    
    }
    

    响应是:

    {
        "id": 49,
        "username": "johndoe",
        "name": "johndoe",
        "first_name": "",
        "last_name": "",
        "email": "johndoe@gmail.com",
        "url": "",
        "description": "",
        "link": "http://localhost/author/johndoe/",
        "locale": "en_US",
        "nickname": "johndoe",
        "slug": "johndoe",
        "roles": [
            "subscriber"
        ],
        "registered_date": "2018-01-13T11:53:57+00:00",
        "capabilities": {
            "read": true,
            "level_0": true,
            "subscriber": true
        },
        "extra_capabilities": {
            "subscriber": true
        },
        "avatar_urls": {
            "24": "http://2.gravatar.com/avatar/29a1df4646cb3417c19994a59a3e022a?s=24&d=mm&r=g",
            "48": "http://2.gravatar.com/avatar/29a1df4646cb3417c19994a59a3e022a?s=48&d=mm&r=g",
            "96": "http://2.gravatar.com/avatar/29a1df4646cb3417c19994a59a3e022a?s=96&d=mm&r=g"
        },
        "meta": {
            "icq": [
                "11223344"
            ]
        },
        "_links": {
            "self": [
                {
                    "href": "http://localhost/wp-json/wp/v2/users/49"
                }
            ],
            "collection": [
                {
                    "href": "http://localhost/wp-json/wp/v2/users"
                }
            ]
        }
    }
    

    如果我想在/wp-admin/ 中显示/编辑,我也只需使用此功能:

    function more_contactmethods( $contactmethods ) {
        $contactmethods['icq'] = 'ICQ';
        return $contactmethods;
    }
    
    add_filter( 'user_contactmethods', 'more_contactmethods' );
    

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2017-01-27
      • 2018-07-25
      • 2016-08-04
      • 2015-10-29
      相关资源
      最近更新 更多