Search code examples
wordpresssoapwsdlcustom-wordpress-pagesposts

Wordpress how to prevent duplicate post by checking if post title exist before running "wp_insert_post"?


I have a wordpress site that connects to a soap server. The problem is every time I run the script the wp_insert_post is using the same result again.

I would like to check if existing post_title matches the value from $title then if they match, prevent wp_insert_post from using the same value again.

Here's the code:

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);

Thank you for any help.


Solution

  • Sorry for the late response. I used what Robot says in the comment and this solved my problem. Thanks

    $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
    }