我有一个名为"notes“的自定义帖子类型,并且在那个名为"page_link”的帖子类型上激活了一个高级自定义字段。我想使用REST添加/编辑page_link的值,但我做不到。我只能编辑像标题和内容这样的本地字段。在我的控制台中,在成功之后,noteLink就在那里,但等于"null“。
我有这样的html:
Title
Content
Linkjavascript:
createNote(e) {
var ourNewPost = {
'title': $(".new-note-title").val(),
'noteLink': $(".new-note-link").val(),
'content': $(".new-note-body").val(),
'status': 'publish'
}
$.ajax({
beforeSend: xhr => {
xhr.setRequestHeader("X-WP-Nonce", myData.nonce)
},
url: myData.root_url + "/wp-json/wp/v2/note/",
type: "POST",
data: ourNewPost,
success: response => {
//location.reload()
console.log("Congrats")
console.log(response)
},
error: response => {
console.log("Sorry")
console.log(response)
}
})
}注册帖子类型如下:
function custom_post_types() {
register_post_type('note', array(
'capability_type' => 'note',
'map_meta_cap' => true,
'show_in_rest' => true,
'supports' => array('title', 'editor', 'advanced-custom-fields'),
'public' => false,
'show_ui' => true,
'labels' => array(
'name' => 'Notes',
'add_new_item' => 'Add New Note',
'edit_item' => 'Edit Note',
'all_items' => 'All Notes',
'singular_name' => 'Note'
),
'menu_icon' => 'dashicons-welcome-write-blog'
));
}register_rest_field在我的functions.php上像这样:
function custom_rest(){
register_rest_field('note', 'noteLink', array(
'get_callback' => function(){return get_field('page_link');}
));
}
add_action("rest_api_init", 'custom_rest');发布于 2021-11-24 04:56:17
我认为这里唯一缺少的是调用register_rest_field中的一个C1。
register_rest_field( 'note', 'noteLink', array(
'get_callback' => function(){ return get_field('page_link'); },
'update_callback' => function( $value, $post ){
update_field('field_619dacfd37924', $value, $post->ID );
}
));根据ACF文档的说法,其中一个重要的部分是在还没有设置值时使用字段键来更新值。
当将新值保存到post时(当不存在值时),应使用字段的键。这有助于ACF在值和字段设置之间创建正确的“引用”。
在编辑字段组时,可以找到该字段的键,但如果您还没有这样做,则可能需要打开该选项,以便在“屏幕选项”中显示“字段键”。然后在字段的表中查找"Key“列。这就是我所看到的。

另外,在注册post类型时,可以将supports属性清除为以下内容:
'supports' => array('title', 'editor'),在那里有“高级-自定义字段”什么也做不了。
https://wordpress.stackexchange.com/questions/398213
复制相似问题