WordPress基于API数据同步更新文章与ACF字段的去重校验方法
可落地的逻辑重构方案
核心匹配规则改造
- 彻底放弃用文章标题做查重依据:标题属于可变展示字段,既可能重复也可能被修改,完全不适合做数据关联的锚点
- 直接用API返回的不可变唯一业务值(比如接口返回的
RefCode/JobId)作为本地文章和API数据的绑定键,给每个同步的文章存api_ref_code自定义元字段,后续查找文章直接按这个元值检索,从根源上避免标题匹配带来的误判
流程分支重构
- 原逻辑的核心缺陷是把「文章分类设置、ACF字段更新」的代码全部写在「文章不存在」的判断块内部,导致已存在的文章永远走不到更新逻辑
- 调整执行流程为:
- 遍历每条API返回的数据,先按绑定键查本地是否有对应文章,拿到对应的文章ID
- 若没有匹配到文章,先新建文章、写入绑定键元值、设置固定分类
- 不管文章是新建的还是已经存在的,统一执行文章基础信息(标题、发布时间)更新、ACF字段同步,保证两边数据一致
原有代码风险点修正
- 修正
wp_set_object_terms参数错误:原代码误将字符串post_tag作为该函数的最后一个参数,实际该位置应为布尔值,决定设置分类时是替换原有分类还是追加分类 - 修复变量覆盖问题:原代码在循环内重新赋值了外层的
$result_data,会干扰外层的遍历逻辑,拆分单条详情的独立变量避免冲突 - 给所有外部API请求加错误捕获,避免接口超时、返回异常时直接触发PHP报错中断执行
效率优化补充
- 给每条同步记录加数据快照:把单条API返回的完整数据生成哈希值存在文章元字段里,每次同步对比新生成的哈希和本地存储的哈希,值一致就直接跳过后续更新操作,减少无意义的数据库写入
修正后的参考代码
if( isset( $_POST['enable'] ) ) { // 请求外层Job列表接口,加错误捕获 $list_api_url = 'https://api.com/test/'; $list_result = @file_get_contents($list_api_url); if (!$list_result) return; $list_data = json_decode($list_result); if (!is_iterable($list_data)) return; foreach ($list_data as $job) { $ref_code = sanitize_text_field($job->RefCode); $job_title = sanitize_text_field($job->JobTitle); $job_date = date('Y-m-d H:i:s', strtotime($job->Published)); // 按API唯一标识检索本地已存在的文章,不再依赖标题匹配 $existing_post = get_posts([ 'post_type' => 'jobs', 'post_status' => 'any', 'posts_per_page' => 1, 'meta_key' => 'api_ref_code', 'meta_value' => $ref_code, 'fields' => 'ids' ]); $post_id = $existing_post[0] ?? 0; // 文章不存在则执行新建 if (!$post_id) { $post_id = wp_insert_post([ 'post_type' => 'jobs', 'post_title' => $job_title, 'post_status' => 'publish', 'post_date' => $job_date, 'post_date_gmt' => get_gmt_from_date($job_date) ]); // 写入API唯一标识绑定关系 update_post_meta($post_id, 'api_ref_code', $ref_code); // 设置默认分类(修正参数为布尔值替换模式) wp_set_object_terms($post_id, 'regulare-job', 'jobscat', false); } // 统一更新文章基础信息,新老文章都执行 wp_update_post([ 'ID' => $post_id, 'post_title' => $job_title, 'post_date' => $job_date, 'post_date_gmt' => get_gmt_from_date($job_date) ]); // 请求单条Job详情接口 $detail_api_url = 'https://api.com/test/' . $ref_code; $detail_result = @file_get_contents($detail_api_url); if (!$detail_result) continue; $job_detail = json_decode($detail_result); // 统一更新ACF字段,新老文章都执行 update_field('location', sanitize_text_field($job->RegionCity), $post_id); update_field('job_intro', sanitize_text_field($job_detail->Intro), $post_id); update_field('job_offer', sanitize_text_field($job_detail->data[0]->Text), $post_id); update_field('job_requirement', sanitize_text_field($job_detail->data[1]->Text), $post_id); update_field('text_c2', sanitize_text_field($job_detail->data[2]->Text), $post_id); update_field('single_job_ref_code', sanitize_text_field($job_detail->RefCode), $post_id); } }
内容的提问来源于stack exchange,提问作者stepbystep
相关产品推荐
相关产品推荐

