You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 06:18:04