Skip to content

Instantly share code, notes, and snippets.

@dingo-d
Created October 26, 2018 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dingo-d/5343334a10ad1b1192e2db5239566e37 to your computer and use it in GitHub Desktop.
Save dingo-d/5343334a10ad1b1192e2db5239566e37 to your computer and use it in GitHub Desktop.
Prevent upload of the same files in media library
<?php
//in media.php class
/**
* Checks if the file with the same name exists in the media library, and renames it if it does
*
* @param array $file An array of data for a single file.
* @return array $file Modified array of data for a single file if the file name is the same.
*/
public function intercept_file_upload( $file ) {
// If, for some odd reason, the file name is empty don't bother with it and let WP handle it.
if ( empty( $file[ 'name' ] ) ) {
return $file;
}
// Only check yaml files, we're not interested in the images.
if ( strpos( $file[ 'name' ], 'yaml' ) === false ) {
return $file;
}
// Search for all the yaml files.
$file_info = pathinfo( $file[ 'name' ] );
$file_name = $file_info[ 'filename' ];
global $wpdb;
$results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' AND post_mime_type = 'application/x-yaml' AND post_title = %s", $file_name ), ARRAY_A );
if ( ! empty( $results ) ) {
$file[ 'error' ] = esc_html__( 'Duplicate names are not allowed', 'plugin_name' );
}
return $file;
}
// in main.php
$this->loader->add_filter( 'wp_handle_upload_prefilter', $this->media, 'intercept_file_upload' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment