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.
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 asked Oct 26, 2012 at 14:16 Dawson GoodellDawson Goodell 2031 gold badge2 silver badges4 bronze badges6 Answers
Reset to default 8global $wpdb;
$image_src = wp_upload_dir()['baseurl'] . '/' . _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
I have this method (thanks Mridul):
function MediaFileAlreadyExists($filename){
global $wpdb;
$query = "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_value LIKE '%/$filename'";
return ($wpdb->get_var($query) > 0) ;
}
// MediaFileAlreadyExists("my-image.png");
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.
// Get upload dir
$upload_dir = wp_upload_dir();
$upload_folder = $upload_dir['path'];
// Set filename, incl path
$filename = "{$upload_folder}/myfile-{$id}.pdf";
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get file title
$title = preg_replace( '/\.[^.]+$/', '', basename( $filename ) );
// Prepare an array of post data for the attachment.
$attachment_data = array(
'guid' => $upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => $title,
'post_content' => '',
'post_status' => 'inherit'
);
// Does the attachment already exist ?
if( post_exists( $title ) ){
$attachment = get_page_by_title( $title, OBJECT, 'attachment');
if( !empty( $attachment ) ){
$attachment_data['ID'] = $attachment->ID;
}
}
// If no parent id is set, reset to default(0)
if( empty( $parent_id ) ){
$parent_id = 0;
}
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment_data, $filename, $parent_id );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
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 it
//if image exist update else create it
if (post_exists($filename)){
$page = get_page_by_title($filename, OBJECT, 'attachment');
$attach_id = $page->ID;
$attach_data = wp_generate_attachment_metadata( $attach_id, $destination ); // Generate attachment data, filesize, height, width etc.
wp_update_attachment_metadata( $attach_id, $attach_data ); // Add the above meta data
add_post_meta($attach_id, '_wp_attachment_image_alt', $filealt); // Add the alt text
}
else{
$attach_id = wp_insert_attachment( $attachment, $destination, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $destination );
wp_update_attachment_metadata( $attach_id, $attach_data );
add_post_meta($attach_id, '_wp_attachment_image_alt', $filealt);
}
I haven't tried it out yet. But it should be as simple as that:
post_exists( $filename, '', '', 'attachment' );
Returns int Post ID if post exists, 0 otherwise.
this function takes as parameter the media file name, and returns the meta_id if it exisists, otherwise it returns (false).
function MediaFileAlreadyExists($filename){
global $wpdb;
$query = "SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_value LIKE '%/$filename'";
if ( $wpdb->get_var($query) ){
return $wpdb->get_var($query);
}
return false;
}