wordpress - 您可以在不使用任何插件的情况下通过 REST API 在新帖子中设置自定义字段吗?
问题描述
我可以使用 REST API 创建帖子,但看不到任何方法可以在不修改源代码的情况下在该帖子上定义自定义字段。
我查看了文档,但没有看到任何支持。看起来你必须自己添加它(没有说在哪里)或者在 REST 调用中发送什么:
我一直在寻找插件,但没有看到任何插件。我见过允许您返回元数据的插件,但所有这些指南都是旧的。
有没有办法在不使用插件或修改源代码的情况下创建或更新新帖子时插入元数据?
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"
}
})
})
上面的代码用于创建帖子,但不会创建自定义字段。
解决方案
从指南看来,开箱即用不支持读取和写入自定义字段。
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"
}
})
})
推荐阅读
- reactjs - D3JS/React - 从每个级别任意数量的子级的链表构造树?
- python-3.x - Python 中的大型 XML 文件解析
- android - 如何修复“重复类 com.google.firebase.components”?
- ios - 如何使用 iOS 13 在 iOS 设备中获取 SSID
- emacs - Emacs 多个 hl 线面/换线钩?
- angular-cli - 当我运行 npm run ng build-hin 时,我遇到错误并且构建失败
- ruby-on-rails - Activeadmin - 如何将当前过滤结果传递给 params 中的自定义操作
- reactjs - 让 reactjs 渲染 textDecoration 的问题:'none'
- paypal - 完成付款后,PayPal SDK 导致“无法捕获订单”错误
- html - “发生错误。请稍后再试”在我的 iframe 中