【问题标题】:Can you set a custom field in a new post through the REST API without using any plugins?您可以在不使用任何插件的情况下通过 REST API 在新帖子中设置自定义字段吗?
【发布时间】:2020-06-19 18:10:50
【问题描述】:

我可以使用 REST API 创建帖子,但看不到任何方法可以在不修改源代码的情况下在该帖子上定义自定义字段。

我查看了文档,但没有看到任何支持。看起来你必须自己添加它(没有说在哪里)或者在 REST 调用中发送什么:

https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#working-with-registered-meta-in-the-rest-api

我一直在寻找插件,但没有看到任何插件。我见过允许您返回元数据的插件,但所有这些指南都是旧的。

有没有办法在不使用插件或修改源代码的情况下创建或更新新帖子时插入元数据?

var results = await fetch(url, {
    method: "POST",
    headers:{
        'Content-Type': 'application/json',
        'accept': 'application/json'
    },
    body: JSON.stringify({
        title: "My Post",
        content: "Hello world!",
        status: 'publish',
        meta: {
            name:"favoriteColor", 
            value: "blue"
        }
    })
})

上面的代码可以创建帖子,但不能创建自定义字段。

【问题讨论】:

标签: wordpress wordpress-rest-api


【解决方案1】:

从指南看来,开箱即用不支持读取和写入自定义字段。

register_meta 用于将现有自定义元值列入白名单 通过 REST API 访问。通过设置元字段的 show_in_rest 参数为 true,该字段的值将在 .meta 键上公开 在端点响应中,和 WordPress 将处理设置 用于读取和写入该元键的回调

所以你必须添加一些php来注册一个元密钥,然后它是可读可写的。

在同一页面上有这个示例代码:

<?php
// The object type. For custom post types, this is 'post';
// for custom comment types, this is 'comment'. For user meta,
// this is 'user'.
$object_type = 'post';
$meta_args = array( // Validate and sanitize the meta value.
    // Note: currently (4.7) one of 'string', 'boolean', 'integer',
    // 'number' must be used as 'type'. The default is 'string'.
    'type'         => 'string',
    // Shown in the schema for the meta key.
    'description'  => 'A meta key associated with a string meta value.',
    // Return a single value of the type.
    'single'       => true,
    // Show in the WP REST API response. Default: false.
    'show_in_rest' => true,
);

register_meta( $object_type, 'my_meta_key', $meta_args );

您可以将其放入您的theme_functions 页面。请参阅外观 > 主题编辑器。

然后在您的代码中定义meta 属性并使用名称值对发送它;键的名称和它的值。

var results = await fetch(url, {
    method: "POST",
    headers:{
        'Content-Type': 'application/json',
        'accept': 'application/json',
        'Authorization': 'Bearer '+ token
    },
    body: JSON.stringify({
        title: pageTitle,
        content: markupOutput,
        status: 'publish',
        meta: {
            my_meta_key: "test"
        }
    })
})

示例代码:
https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#read-and-write-a-post-meta-field-in-post-responses

文档:
https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#using-register_rest_field-vs-register_meta

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多