如何在save_post钩子中通过现有WP API更新ACF字段
WordPress 原生REST API更新目标站点元数据/ACF字段方案
前置准备:目标站点配置
默认WordPress REST API不开放自定义元字段的修改权限,必须在目标站点添加以下代码,让需要更新的字段(包括ACF字段)支持REST操作:
// 目标站点functions.php或自定义插件中添加 add_action('rest_api_init', function () { // 替换为你实际要更新的ACF字段键名 $target_meta_key = 'full_content'; register_meta('post', $target_meta_key, array( 'show_in_rest' => true, 'single' => true, 'type' => 'string', // 根据字段类型调整:text/array/number等 'auth_callback' => function () { // 限制只有有权限编辑文章的用户能修改 return current_user_can('edit_posts'); } )); });
注:ACF字段的键名就是你在ACF后台设置的“字段名称”,如果是默认生成的field_xxxxxx格式也可以直接用。
源站点请求代码修改
原代码用了wp_remote_post但没指定PUT方法,且缺少请求体数据,修改后如下:
function publish_content($post_id, $post, $update) { // 跳过文章修订版本,避免重复触发 if (wp_is_post_revision($post_id)) { return; } // 获取本地要同步的ACF字段值 $full_content = get_field('full_content', $post_id); if (empty($full_content)) { return; // 字段为空时直接返回,不发起请求 } // 目标站点的认证信息和文章ID $login = 'username'; $password = 'password'; $target_post_id = 12; $target_api_url = "https://example.com/wp-json/wp/v2/posts/{$target_post_id}"; // 构建请求参数 $request_args = array( 'headers' => array( 'Authorization' => 'Basic ' . base64_encode("$login:$password"), 'Content-Type' => 'application/json' // 必须指定JSON格式 ), 'method' => 'PUT', // REST API更新资源用PUT方法 'body' => json_encode(array( 'meta' => array( 'full_content' => $full_content // 对应目标站点注册的字段键名 ) )) ); // 发起请求 $response = wp_remote_post($target_api_url, $request_args); // 可选:处理请求结果(日志记录) if (is_wp_error($response)) { error_log('同步目标站点字段失败: ' . $response->get_error_message()); } else { $response_code = wp_remote_retrieve_response_code($response); if ($response_code === 200) { error_log('目标站点字段同步成功'); } else { error_log('同步失败,响应码: ' . $response_code); } } } add_action('save_post', 'publish_content', 11, 3);
核心注意点
- 请求方法:更新文章必须用
PUT,不能用默认的POST(POST是创建资源)。 - 权限验证:目标站点的账号必须拥有
edit_posts权限,且确保目标站点启用了Basic Auth(可通过WP Basic Auth插件快速启用,或改用JWT认证)。 - 复杂ACF字段处理:如果是 repeater、灵活内容这类复杂ACF字段,需要保证传入的数组结构和ACF在数据库中存储的结构完全一致,否则目标站点的ACF无法正确解析显示。
内容的提问来源于stack exchange,提问作者Pedram Nasertorabi
相关产品推荐
相关产品推荐

