首页 > 解决方案 > 您可以在不使用任何插件的情况下通过 REST API 在新帖子中设置自定义字段吗?

问题描述

我可以使用 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"
        }
    })
})

上面的代码用于创建帖子,但不会创建自定义字段。

标签: wordpresswordpress-rest-api

解决方案


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

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


推荐阅读