Bhavin Toliya
Bhavin Toliya

Reputation: 17

I want to compare post titles and if no match found then create new post with php in wordpress

I have created following script to creates a new post from CJ web api if post already not exits with sane advertiser name but script does it without checking post exits or not. ie. their is no if...else effect, so how can I fix that ? I am new to PHP so please ignore my noobsense, thanks.

      foreach ($data->products[0] as $product) 
    {
        // Sanitize data.
        $price = number_format((float)$product->price, 2, '.', ' ');
        $image = '<a href="'.$product->{'buy-url'}.'"><img src="'.$product->{'image-url'}.
        '" style="float: right"/></a>';
        $pd =  $image.$product->description .'<a href="'.$product->{'buy-url'}.
        '">...For more details and to buy it click here</a>';

        $post_slug = $product->{'advertiser-name'};
        $args=array(
            'cat' => $_GET['cat'],
            'name' => $post_slug,
            'post_type' => 'post',
            'post_status' => 'publish'
                    );
        $my_query = new WP_Query($args);
        if($my_query->have_posts()) {
            echo 'post already exits';
            wp_reset_query();  // Restore global post data stomped by the_post().
}           
            else{

                $p = array('post_title'    => $product->{'advertiser-name'},
  'post_content'  => $pd,
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category'  =>array($_GET['cat']));
    $pr = wp_insert_post( $p, $wp_error );
    echo $pr;
    wp_reset_query();  // Restore global post data stomped by the_post().

}

Upvotes: 0

Views: 111

Answers (1)

Mark Richards
Mark Richards

Reputation: 434

any values come in $my_query->have_posts() ?

first check it.

try print_r($my_query->have_posts());

then try to do in if(){ ...}else { ....}

Upvotes: 0

Related Questions