Check Attachment Existence WordPress Tutorial

Posted On: October 3, 2017

If you want to CHECK the same attachment name exists already before creating a new one or before inserting the attachment into the DB, you can use the following method:

// check if attachment already exists

$attachment_args = array(   
     ‘posts_per_page’ => 1,     
     ‘post_type’      => ‘attachment’,    
     ‘name’           => $desc  
  );

$att_check = new Wp_Query( $att_args );     // if attachment exists, reuse and update data

if ( $att_check->have_posts() ) {

echo ‘Attachment <strong>’. $desc .'</strong> found…<br>’;

// do stuff..

// if attachment doesn’t exist

} else {

echo ‘Attachment <strong>’. $desc .'</strong> not found…<br>’;         // handle image upload from url and assign to post

$src = media_sideload_image( $url, $post_id, $desc, ‘src’ );         // add post meta

if ( $ca[‘imgGo’] == $url  ) {

add_post_meta( $post_id, ‘imgGo’, $src );

} else {

add_post_meta( $post_id, ‘img’, $src );

}

 

Related Post

Also Read :   Best Search Engine Optimization Company India
X
Subscribe to our newsletter
Subscribe to our newsletter today to receive updates on the latest news and offers.
100% Privacy. No spam guaranteed
webe tutorial
Menu