Checking if a file is already in the Media Library

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