2011-10-04 54 views
5

我有一個連接到肥皂服務器的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); 

感謝您的任何幫助。

+2

你應該試試這個代碼。 require(dirname(__ FILE__)。'/wp-load.php'); global $ wpdb; echo $ count = $ wpdb-> get_var(「select $ COUNT(*)from $ wpdb-> posts'post_title' like'$ title'」); – Robot

回答

4

對不起,我遲到的反應。我使用了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 
} 
13

您可以使用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

+2

我喜歡這種利用內置函數獲得最佳結果的方法。我相信第一行應該是:「if(!get_page_by_title($ title,OBJECT,'skarabeepublication')):」 – Jake

+0

你絕對正確,謝謝! – CookiesForDevo

+0

'OBJECT'不應該有撇號,但否則這種方法完美的工作,並仍然是有效的WordPress的4.7.3。 – Arinthros

4

驚訝沒有看到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 
} 
+0

Wordpress開發人員代碼參考中現在有一個[post_exists中的條目](https://developer.wordpress.org/reference/functions/post_exists/)。 – Jon

0

採樣:

if(!get_page_by_path('mypageslug',OBJECT,'post')){ 
    //your codes 
} 
相關問題