WP - 在 wp_insert_post 之前检查帖子是否存在 [英] WP - check if post exists before wp_insert_post
问题描述
如何在wp_insert_post之前检查帖子是否存在以避免重复?
How to check if the post exists before wp_insert_post to avoid duplication?
如果我删除if"语句(post_exists())并继续重新插入产生多个重复的帖子,则下面的代码有效.我用 post_exists() 编写了 if 语句只是为了开始实现检查的逻辑,但是当我添加 if 语句时,有些东西中断了,下面的列表甚至没有打印出来.
The code below works if I remove the 'if' statement (post_exists()) and just keep reinserting posts producing multiple duplications. I wrote the if-statement with post_exists() just to start implementing the logic of checking but the moment I add the if statement, something breaks and the list below doesn't even get printed.
$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
please see the $data_events array: https://pastebin.com/rC60iNyJ
推荐答案
post_exists()
函数在前端通常不可用.您可以使用 get_page_by_title
来按标题查找帖子,而不是包含另一个文件.只需测试 null
值以检查它是否不存在.
The post_exists()
function is not normally available on the front end. Instead of including another file you can use get_page_by_title
to find a post by it's title. Just test for a null
value to check if it doesn't exist.
替换
if ( post_exists( $event['name'] ) == 0 ) {
与
if ( get_page_by_title( $event['name'] ) == null ) {
这篇关于WP - 在 wp_insert_post 之前检查帖子是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!