Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

1 Answer 1

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

 
discard

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.