提问人:jeffmayn 提问时间:10/26/2023 最后编辑:jeffmayn 更新时间:10/30/2023 访问量:55
如何在 Wordpress JavaScript 函数中使用 Ajax POST 将数据插入 ACF 字段?
How do I insert data into an ACF-field with an Ajax POST in a Wordpress JavaScript function?
问:
我正在做什么:带有 ACF 插件和 JavaScript 的 Wordpress。
我想做的是:创建一个帖子并设置标题、内容、状态和一些 ACF 字段。
什么是输出:它成功创建了帖子,但只设置了标题和内容。ACF 字段为空。
我尝试过哪些替代方案:尝试将“acf_fields:”更改为“fields:”,但没有运气。
问:我是否为 ACF 字段使用了错误的标签?或者有其他方法可以做到这一点吗?
createMarker(latitude, longitude) {
var ourNewPost = {
title: latitude + ", " + longitude,
content: "Coordinates: " + latitude + ", " + longitude,
status: "publish",
acf_fields: {
points_title: "test",
points_latitude: latitude.toString(),
points_longitude: longitude.toString(),
status: 0
},
};
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader("X-WP-Nonce", myData.nonce);
},
url: myData.root_url + "/wp-json/wp/v2/points/",
type: "POST",
data: ourNewPost,
success: (response) => {
console.log(response);
},
error: (response) => {
console.log(response);
},
});
}
定义我的自定义帖子类型:
function points(){
register_post_type('points', array(
'show_in_rest' => true,
'map_meta_cap' => true,
'supports' => array('title', 'editor','custom-fields'),
'show_ui' => true,
'public' => true,
'labels' => array(
'name' => 'Points'
)
));
}
add_action('init', 'points');
答:
1赞
Vimal Usadadiya
10/26/2023
#1
您必须在保存后调用 hook,然后您可以在 hook 中编写代码来填充 acf 字段数据。
add_action('acf/save_post', 'set_acf_data');
function set_acf_data($post_id)
{
$acf_data= "Your Data which you want to add in ACF field";
if ('post' == get_post_type($post_id)) {
update_field('acf_key', $acf_data, $post_id);
}
}
评论
0赞
jeffmayn
10/26/2023
我将其添加到函数.php中,对吗?如何从 ajax 调用中调用钩子?
0赞
Vimal Usadadiya
10/26/2023
保存帖子时 Hook 会自动调用,无需使用 ajax 调用。
0赞
jeffmayn
10/26/2023
似乎无法让它工作。我如何从这个钩子中的ajax调用中读取points_title?
0赞
disinfor
10/30/2023
#2
问题出在您的功能上。ACF 字段的对象字段键不正确 - 它应该只是:CreateMarker
acf
createMarker(latitude, longitude) {
var ourNewPost = {
title: latitude + ", " + longitude,
content: "Coordinates: " + latitude + ", " + longitude,
status: "publish",
acf: {
points_title: "test",
points_latitude: latitude.toString(),
points_longitude: longitude.toString(),
status: 0
},
};
下面是显示整个字段的文档链接。POST
评论
acf
fields
acf_fields