Checking if a file is already in the Media Library

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'] . "https://wordpress.stackexchange.com/" . _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.

6 s
6

global $wpdb;
$image_src = wp_upload_dir()['baseurl'] . "https://wordpress.stackexchange.com/" . _wp_relative_upload_path( $filename );
$query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE guid='$image_src'";
$count = intval($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

Leave a Comment