WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm creating custom files in a plugin and adding them to the Media Library using the code provided in the Wordpress Codex for wp_insert_attachment. However, my plugin occasionally overwrites those files. I need to make sure that the files are not added again to the Media Library. Here is the current code:

$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
   'guid' => $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path( $filename ), 
   'post_mime_type' => $wp_filetype['type'],
   'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
   'post_content' => '',
   'post_status' => 'inherit'
$attach_id = wp_insert_attachment( $attachment, $filename);
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

I just need to check whether or not the file is already a part of the Media Library, and update it if it is. I do not have a post_id to work with, just the permalink and the guid.

Thanks for your help.

share|improve this question
up vote 1 down vote accepted
global $wpdb;
$image_src = $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path( $filename );
$query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE guid='$image_src'";
$count = $wpdb->get_var($query);

You can use this at the top of your code. Then check the value of $count. If it's 0, then you can continue adding the attachment

share|improve this answer
Works great. Thanks! – OSMman Oct 26 '12 at 17:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.