我正在尝试迭代一些API数据,并将其转换为自定义WordPress帖子。
我的功能正常,但是我不能阻止它创建重复的帖子。
我在每次迭代中都检查一个唯一的unitproperty_id
字段,以避免创建重复项,但是它只能以偶发方式工作。
有时不会有重复的帖子,有时会有两个,有时三个。
它也仅在第一次通过时发生,在创建帖子(重复和非重复)后,它不会每次都保持创建状态。重复项仅在第一次加载时出现。
当此函数正常工作时,我将定期使用wp_cron
作业对其进行调用,但在此之前,我将使用shutdown
操作钩子对其进行调用,该钩子将在WordPress加载。
您知道为什么我会生成重复的帖子吗?
add_action( 'shutdown', 'build_units_from_api', 10 );
function build_units_from_api() {
//Get all the unit IDs currently inside wordpress
$current_property_ids = array();
$wp_units = get_all_wp_posts('unit');
foreach ($wp_units as $wp_unit) {
$current_property_ids[] = (int)get_post_meta( $wp_unit->ID, 'unitproperty_id', true );
}
//Get all the api data
$property_units = get_all_property_units();
$num_of_property_pages = $property_units['pages'];
//Loop through the pages of the API data
for ( $i=0; $i <= $num_of_property_pages; ++$i ) {
$page_of_units = get_property_units_by_page($i);
$num_of_units_on_page = count($page_of_units['results']);
//Loop through the results of each page
for ( $x=0; $x <= $num_of_units_on_page; ++$x ) {
$property_profile = $page_of_units['results'][$x];
//Check if we already have that unit property ID
if ( in_array($property_profile['id'], $current_property_ids, true) || $property_profile['id'] == null ) {
//Do nothing and exit the current iteration
continue;
} else {
//Get the individual profile info from unit property API
$api = new unitpropertyAPI();
$api->getunit($property_profile['id']);
$property_profile_data = json_decode($api->result, true);
$post_arr = array(
'post_type' => 'unit',
'post_title' => $property_profile_data['name'],
'post_content' => '',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'meta_input' => array(
'unitproperty_id' => $property_profile_data['id'],
'unit_name' => $property_profile_data['name'],
'unitproperty_rating' => $property_profile_data['rating'],
),
);
//Put those fields into a new 'unit' custom post
$new_id = wp_insert_post( $post_arr );
//Stop from adding this property again
$current_property_ids[] = $property_profile_data['id'];
}
}
}
}
答案 0 :(得分:0)
那是动作钩!
由于以下答案,我找到了解决方案:https://wordpress.stackexchange.com/questions/287599/wp-insert-post-creates-duplicates-with-post-status-publish
将动作挂钩更改为admin_notices
可以解决此问题,因为它不会在wp_insert_post
调用期间重新触发。