如何检查 wp_insert_post 之前的帖子是否存在以避免重复?
如果我删除“if”语句(post_exists())并继续重新插入产生多个重复的帖子,下面的代码就可以工作。我用 post_exists() 编写了 if 语句,只是为了开始实现检查逻辑,但是当我添加 if 语句时,某些东西就会中断,下面的列表甚至不会被打印。
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'exists';
} else {
echo 'doesnt exist';
}
echo '<li>';
echo $event['id'];
echo '<a href="' . esc_url( $event['uri'] ) . '">' . $event['name'] . '</a>';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
?>
编辑:请查看 $data_events 数组:https://pastebin.com/rC60iNyJ https://pastebin.com/rC60iNyJ
The post_exists()
前端通常不提供此功能。您可以使用而不是包含另一个文件get_page_by_title
通过标题查找帖子。只需测试一个null
值来检查它是否不存在。
Replace
if ( post_exists( $event['name'] ) == 0 ) {
with
if ( get_page_by_title( $event['name'] ) == null ) {
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)