如何在WordPress的JavaScript函数中通过Ajax POST向ACF字段插入数据?
解决ACF字段通过WP REST API创建文章时不生效的问题
核心原因
ACF字段不会自动纳入WordPress默认的REST API端点,需要手动配置才能支持通过API读写ACF字段,同时请求数据的格式也需要调整。
修复步骤
1. 添加PHP代码支持ACF字段的REST API读写
将以下代码添加到主题的functions.php文件中,用于为points自定义文章类型启用ACF字段的REST API支持:
function enable_acf_rest_for_points() { // 允许通过REST API更新ACF字段 add_action('rest_insert_points', function($post, $request, $creating) { if (isset($request['acf']) && is_array($request['acf'])) { foreach ($request['acf'] as $field_key => $field_value) { update_field($field_key, $field_value, $post->ID); } } }, 10, 3); // 可选:将ACF字段加入REST API返回结果(方便后续获取) add_filter('rest_prepare_points', function($response, $post, $request) { $acf_fields = get_fields($post->ID); if ($acf_fields) { $response->data['acf'] = $acf_fields; } return $response; }, 10, 3); } add_action('init', 'enable_acf_rest_for_points');
2. 修正JavaScript请求代码
需要调整两个关键点:
- 将
acf_fields改为acf作为ACF字段的键名 - 将请求数据转为JSON格式发送(嵌套对象无法通过表单编码正确传递)
修正后的代码:
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 }, }; $.ajax({ beforeSend: (xhr) => { xhr.setRequestHeader("X-WP-Nonce", myData.nonce); }, url: myData.root_url + "/wp-json/wp/v2/points/", type: "POST", contentType: "application/json", // 指定JSON内容类型 data: JSON.stringify(ourNewPost), // 将数据转为JSON字符串 success: (response) => { console.log(response); }, error: (response) => { console.log(response); }, }); }
3. 额外检查事项
- 确保你的
nonce拥有wp_rest权限,验证用户具备创建points文章的权限 - 确认ACF字段的键名(如
points_title)完全匹配你在ACF后台创建的字段键(注意不是字段标签)
内容的提问来源于stack exchange,提问作者jeffmayn
相关产品推荐
相关产品推荐

