Prevent Duplicate Attachment When Using wp_insert_post

I am trying to use wp_insert_attachment while using wp_insert_post. It’s successfully creating the post and attachment. It have no problem if I only use the wp_insert_post function, but when I activating the wp_insert_attachemnt, the script create both, duplicate posts and attachments 3 times of the previous created posts and attachments.

Here is the code (UPDATED):

Read More
add_action('admin_menu', 'awpht_admin_opt');

function awpht_admin_opt() {
    add_plugins_page('AWPHT Control', 'Automatic Photoblog', 'manage_options', 'awpht_option_control', 'awpht_option_control_page');
}
function enqueue_awpht_style() {
    wp_register_style( 'awpht_admin_style', plugins_url('awpht-main.css', __FILE__) );
    wp_enqueue_style('awpht_admin_style');
}

add_action( 'admin_enqueue_scripts', 'enqueue_awpht_style' );


//Administration Menu
function awpht_option_control_page() {
?>


<div id="">
<h1>Automatic Photoblog</h1>
<form method="post" action="">
<table>
<tr><td>Post Category</td><td><input type="text"/></td></tr>
<tr><td>Post Status</td><td><select name="awpht_post_status">
<option>Publish</option>
<option>Draft</option>
</select></td></tr>
</table>

<input type="submit" name="awpht-create-posts" class="button button-primary button-large" id="awpht-create-posts" value="Create Posts"/>
</form>

</div>


<?php
if (isset($_POST['awpht-create-posts'])) {

//Get Images Folder Path
$awphtdir = wp_upload_dir();
$awphtimgdir = $awphtdir['basedir'];
$upload_path = $awphtimgdir."/photoblog/";


$awpharritle = array();
$awpht_content = array();
$awphtfname = array();
$attch_imgurl = array();
$attch_title = array();
$attch_fname = array();


// Fetch Images Names From Folder
foreach(glob($upload_path."*.*") as $filename){
$attch_fname[] = $awphtdir['basedir']."/attachments/".basename($filename);
// Filwname with extension
$allfname = basename($filename);
$awphtfname[] = $allfname;

//Filename without Extension
$awpht_title = preg_replace("/\.[^.\s]{3,4}$/", "",basename($filename));
$attch_title[] = $awpht_title;
$adspc = array("-", "_", ".");

//Post Title
$awphttitle = str_replace($adspc, " ", $awpht_title);
$awpharritle[] = $awphttitle;

//Get image url
$awpht_dir = wp_upload_dir();
$awpht_imgurl = $awpht_dir['baseurl'].'/photoblog/'.$allfname;
$attch_imgurl[] = $awpht_imgurl;

//Post Content
$awpht_content[] = "<img src='".$awpht_imgurl."'/>";
        }

//Create Posts With The Available Data
$year = '2014';
$postdate = $postdate = date($year.'-02-23 18:57:33');
$awpht_length = count($awpharritle);

for($i=0; $i<$awpht_length; $i++ ) {

//Check If Post Already Exist/ Prevent Duplicates
if (!get_page_by_title($awpharritle[$i], 'OBJECT', 'post')){

$awpht_the_posts[$i] = array(
  'post_title'    => $awpharritle[$i],
  'post_content'  => $awpht_content{$i},
  'post_date'     =>   $postdate,
  'post_status'   => 'publish',
  'post_author'   => 1,
);
// Insert the post into the database
$post_id = wp_insert_post( $awpht_the_posts[$i]);

//Set category and tag
wp_set_post_terms( $post_id , 2 ,  'category' );
wp_set_post_terms( $post_id , 'test, text, play' ,  'post_tag' );


//INSERT ATTACHMENT
$awpht_filetype = wp_check_filetype($awphtfname[$i], null );
$awpht_attachment = array(
        'guid' => $attch_imgurl[$i],
        'post_mime_type' => $awpht_filetype['type'],
        'post_type' => 'attachment',
        'post_title' => $attch_title[$i],
        'post_content' => '',
        'post_status' => 'inherit'
                    );  
$awphtattach_id = wp_insert_attachment( $awpht_attachment, $attch_fname[$i], $post_id );


//Create thumbnail with resized images
require_once(ABSPATH . 'wp-admin/includes/image.php');                
$awphtattach_data = wp_generate_attachment_metadata( $awphtattach_id, $attch_fname[$i] );
wp_update_attachment_metadata( $awphtattach_id, $awphtattach_data );


// Set Featured Image
set_post_thumbnail( $post_id, $awphtattach_id);
//update_post_meta($post_id, '_thumbnail_id', $awphtattach_id);
echo get_the_post_thumbnail($post_id, 'thumbnail'); 
            }
        }
    }   
}

My question:
How to prevent the script from creating duplicate attachments and posts?

Best Regards

Related posts