背景:自定义帖子(类型:Event)可以由用户手动添加(在这种情况下不存在hq_id元数据),也可以由wp_insert_post()自动添加(从另一个源提取)(在这种情况下存在hq_id)。
有些时候,帖子可以有通用标题,所以在插入帖子之前,检查是否存在特定标题的帖子是不够的。下面的想法是:
在尝试从其他来源插入帖子并将其与用户手动添加的帖子合并之前,请检查以下内容:
-
是否存在同名帖子?
a) 否=>让我们插入它(结束)
b) 对。
-
如果是:它是否有hq_id元数据,这是否等于要插入的帖子的hq_id元数据。
a) 是=>好的,这是一篇重复的帖子,不需要插入
b) 否=>存在同名帖子,但hq_id不存在或不同,因此它不是重复的。让我们插入它。
这很好,直到你再次运行代码。每次它似乎都在添加符合2b条件的帖子。
对于代码的每次重新运行,2a和2b都是真的。我不确定为什么它在2a之后不退出if语句,但它仍然退出2b语句。
此外,正如您将看到的那样,整个$new_post/wp_insert_post代码块应该被移动到一个函数中,因为它被使用了两次。我应该把函数定义放在哪里,这样我就不会在范围上有问题了?
以下是代码:
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
$title_exists = get_page_by_title( $event['name'], OBJECT, 'event');
if ( $title_exists == null ) {
echo 'Post of the same title does not exist - we need to insert post';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'desssscccd',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'event',
'meta_input' => array(
'hq_id' => $event['id'],
'hq_uri'=> $event['uri'],
)
);
$pid = wp_insert_post($new_post);
wp_set_object_terms($pid, 'riderhq', 'event_category');
} else { // A post of the same title exists
$my_post = get_page_by_title ( $event['name'], OBJECT, 'event' );
$post_hq_id = $my_post->hq_id;
if ( $post_hq_id && $post_hq_id == $event['id'] ) {
echo "post of the same title exists and has the same hq_id - no need to insert it";
} else {
echo "post of the same title exists but doesnt have the same hq_id - we need to insert it";
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'event',
'meta_input' => array(
'hq_id' => $event['id'],
'hq_uri'=> $event['uri'],
)
);
$pid = wp_insert_post($new_post);
wp_set_object_terms($pid, 'riderhq', 'event_category');
}
}
echo '<li>';
echo $event['id'];
echo '<a href="' . esc_url( $event['uri'] ) . '">' . $event['name'] . '</a>';
echo '</li>';
}
echo '</ul>';
}