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.
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 attachmentI have this method (thanks Mridul):
I know this is a old question but I didn’t like any of these answers so here is my solution.
This will check if the file exists. If so it will update the existing attachment; if not, it will create a new attachment.
In the example above I’m using a .pdf in my $filename but you can replace this with any filename/filetype.
You can check if image exist with
post_exists($filename)
. If image exist you can update it also you can create itI haven’t tried it out yet. But it should be as simple as that:
Returns int Post ID if post exists, 0 otherwise.