使用wp_insert_post/wp_update_post从JSON导入时重复创建内容的问题
问题排查与修复
核心问题
你当前代码中重复创建内容的根源是get_page_by_title默认只查询page类型的内容,而你的自定义内容类型是training,导致每次运行导入器时,系统都找不到已存在的training帖子,进而执行wp_insert_post重复创建。
具体修复步骤
1. 修正内容存在性检查逻辑
将get_page_by_title调用添加post_type参数,明确指定查询training类型:
// 原代码 $check_title = get_page_by_title( $name); // 修改后 $check_title = get_page_by_title( $name, OBJECT, 'training' );
2. 优化代码冗余(可选)
当$check_title不为空时,wp_update_post已经会处理tax_input,可以移除额外的wp_set_object_terms调用;插入新内容时,my_post数组里已经包含tax_input,也可以省略单独的wp_set_object_terms。优化后的导入器代码:
$check_title = get_page_by_title( $name, OBJECT, 'training' ); $my_post = array( 'ID' => $check_title ? $check_title->ID : 0, 'post_title' => wp_strip_all_tags($name), 'post_type' => 'training', 'post_content' => $desc, 'post_status' => 'publish', 'post_author' => 1, 'comment_status' => 'closed', 'ping_status' => 'closed', 'meta_input' => array( 'course_type' => $type, 'tutor' => $tutor, 'location' => $location, 'planned_start' => $planned_start, 'actual_start' => $actual_start, 'actual_end' => $actual_end, 'max_attendees' => $max_attendees, ), 'tax_input' => array( 'custom_cat_training' => $type, ), ); if (empty($check_title)){ $post_id = wp_insert_post($my_post); } else { $post_id = wp_update_post($my_post); }
3. 进阶优化:使用唯一标识替代标题检查(推荐)
如果JSON数据中包含唯一ID(比如course_id),可以通过自定义字段来检查内容是否存在,比标题检查更可靠(避免标题重复或大小写/空格差异导致的误判):
// 假设JSON中有唯一字段$course_id $existing_post = get_posts(array( 'post_type' => 'training', 'meta_key' => 'course_unique_id', 'meta_value' => $course_id, 'posts_per_page' => 1, 'post_status' => 'publish' )); $check_title = !empty($existing_post) ? $existing_post[0] : null; // 后续逻辑同上,同时在meta_input中添加'course_unique_id' => $course_id
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

