WordPress调用wp_insert_post()如何通过ACF字段避免文章重复插入
基于ACF自定义字段的重复判断调整方案
核心调整逻辑
将原有的基于文章slug的重复校验,替换为针对存储API端唯一记录ID的ACF字段的查询校验,彻底避免因为文章标题修改导致的重复插入问题。
前置约定(可根据你的实际情况修改)
- 你用来存储API端展商唯一ID的ACF字段名为
api_exhibitor_id - API返回的展商数据中,唯一ID对应的数组键为
id
修改后完整代码
add_action( 'wp_ajax_nopriv_post_exhibitors_from_api', 'post_exhibitors_from_api' ); add_action( 'wp_ajax_post_exhibitors_from_api', 'post_exhibitors_from_api' ); function post_exhibitors_from_api() { $exhibitors = $curl_test_list_array; foreach ($exhibitors as $exhibitor) { $exhibitor_title = $exhibitor['name']; $exhibitor_slug = sanitize_title($exhibitor_title); // 替换原有get_page_by_path逻辑:基于ACF存储的API唯一ID查询已存在的文章 $existing_posts = get_posts([ 'post_type' => 'exhibitors', 'posts_per_page' => 1, 'meta_key' => 'api_exhibitor_id', 'meta_value' => $exhibitor['id'], // 替换为你API返回的唯一ID对应键名 'post_status' => 'any', 'fields' => 'ids' // 仅返回文章ID,大幅提高查询效率 ]); $exhibitor_existing_id = $existing_posts ? $existing_posts[0] : null; if ($exhibitor_existing_id === null) { // 无匹配记录,执行插入 $exhibitor_inserted = wp_insert_post([ 'post_name' => $exhibitor_slug, 'post_title' => $exhibitor_title, 'post_type' => 'exhibitors', 'post_status' => 'publish' ]); if (is_wp_error($exhibitor_inserted)) { continue; } get_exhibitors_acf_fields($exhibitor, $exhibitor_inserted); } else { // 存在匹配记录,判断更新时间决定是否更新字段 $exhibitor_existing_timestamp = get_field('maj_exposant', $exhibitor_existing_id); if ($exhibitor['updated_at'] >= $exhibitor_existing_timestamp) { get_exhibitors_acf_fields($exhibitor, $exhibitor_existing_id); } } } }
注意事项
- 请确保你的
get_exhibitors_acf_fields函数已经实现了将API返回的唯一ID写入对应ACF字段(也就是上面的api_exhibitor_id)的逻辑,否则查询会失效 - 如果API返回的唯一ID为数字类型,可以在
get_posts的参数中新增'meta_type' => 'NUMERIC',提高查询的准确性 - 如果需要更高的查询效率,可以给
wp_postmeta表的meta_key和meta_value字段加联合索引
内容的提问来源于stack exchange,提问作者Jandon
相关产品推荐
相关产品推荐

