Created
October 26, 2018 11:50
-
-
Save dingo-d/5343334a10ad1b1192e2db5239566e37 to your computer and use it in GitHub Desktop.
Prevent upload of the same files in media library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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