如何通过在运行“wp_insert_post”之前检查帖子标题是否存在来防止重复帖子?
我有一个连接到肥皂服务器的wordpress网站。问题是每次运行脚本时,“wp_insert_post”都会再次使用相同的结果。我想检查现有的post_title是否与$ title的值匹配,如果它们匹配,请防止wp_insert_post再次使用相同的值。如何通过在运行“wp_insert_post”之前检查帖子标题是否存在来防止重复帖子?
下面的代码:
try {
$client = new SoapClient($wsdl, array('login' => $username, 'password' => $password));
} catch(Exception $e) {
die('Couldn\'t establish connection to weblink service.');
}
$publications = $client->GetPublicationSummaries();
foreach ($publications->GetPublicationSummariesResult->PublicationSummaries->PublicationSummary as $publication_summary) {
// get the complete publication from the webservice
$publication = $client->getPublication(array('PublicationId' => $publication_summary->ID))->GetPublicationResult->Publication;
// get all properties and put them in an array
$properties = array();
foreach ($publication->Property as $attribute => $value) {
$properties[$attribute] = $value;
}
// Assemble basic title from properties
$title = $properties['Address']->Street . ' ' . $properties['Address']->HouseNumber . $properties['Address']->HouseNumberExtension . ', ' . $properties['Address']->City->_;
}
$my_post = array(
'post_title'=>$title,
'post_content'=>'my contents',
'post_status'=>'draft',
'post_type'=>'skarabeepublication',
'post_author'=>1,
);
wp_insert_post($my_post);
感谢您的任何帮助。
对不起,我迟到的反应。我使用了Robot在评论中所说的话,这解决了我的问题。由于
$post_if = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title like '$title_from_soap'");
if($post_if < 1){
//code here
}
您可以使用get_page_by_title()
,因为它现在支持自定义帖子类型。
if (!get_page_by_title($title, OBJECT, 'skarabeepublication')) :
$my_post = array(
'post_title'=>$title,
'post_content'=>'my contents',
'post_status'=>'draft',
'post_type'=>'skarabeepublication',
'post_author'=>1,
);
wp_insert_post($my_post);
endif;
食品信息here
我喜欢这种利用内置函数获得最佳结果的方法。我相信第一行应该是:“if(!get_page_by_title($ title,OBJECT,'skarabeepublication')):” – Jake
你绝对正确,谢谢! – CookiesForDevo
'OBJECT'不应该有撇号,但否则这种方法完美的工作,并仍然是有效的WordPress的4.7.3。 – Arinthros
惊讶没有看到post_exists
功能提到WP-包括/ post.php中。见entry on wpseek。法典中没有条目。最简单的就像get_page_by_title
,但返回一个帖子id(或者如果找不到,则返回0)而不是对象(或null)。
$post_id = post_exists($my_title);
if (!$post_id) {
// code here
}
Wordpress开发人员代码参考中现在有一个[post_exists中的条目](https://developer.wordpress.org/reference/functions/post_exists/)。 – Jon
采样:
if(!get_page_by_path('mypageslug',OBJECT,'post')){
//your codes
}
你应该试试这个代码。 require(dirname(__ FILE__)。'/wp-load.php'); global $ wpdb; echo $ count = $ wpdb-> get_var(“select $ COUNT(*)from $ wpdb-> posts'post_title' like'$ title'”); – Robot