Last active
December 12, 2017 15:15
-
-
Save mircian/f21b993646051808527bd7d38ab87499 to your computer and use it in GitHub Desktop.
Change the name of files uploaded through the media uploader.
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 | |
/** | |
* Class M_Custom_Uploads_Filename | |
*/ | |
class M_Custom_Uploads_Filename { | |
/** | |
* M_Custom_Uploads_Filename constructor. | |
*/ | |
public function __construct() { | |
$this->hooks(); | |
} | |
/** | |
* Add the hooks used by the class. | |
*/ | |
public function hooks() { | |
add_action( 'current_screen', array( $this, 'maybe_mark_upload' ) ); | |
add_filter( 'sanitize_file_name', array( $this, 'maybe_change_filename' ), 10, 2 ); | |
} | |
/** | |
* Check if we are in the right screen and add a filter for the media upload requests. | |
* | |
* @param WP_Screen $screen The current screen object. | |
*/ | |
public function maybe_mark_upload( $screen ) { | |
// Check the screen id | |
if ( isset( $screen->id ) && 'toplevel_page_m-admin-page' === $screen->id ) { | |
add_filter( 'plupload_default_params', array( $this, 'add_uploads_parameter' ) ); | |
} | |
} | |
/** | |
* Add the custom parameter to the set of default upload parameters. | |
* | |
* @param array $parameters The default parameters | |
* | |
* @return array | |
*/ | |
public function add_uploads_parameter( $parameters ) { | |
$parameters['m_admin_page'] = 1; | |
return $parameters; | |
} | |
/** | |
* Check if the custom paramter set above is set and change the filename accordingly. | |
* | |
* @param string $filename The processed filename after sanitize filename function was called | |
* @param string $filename_raw | |
* | |
* @return string | |
*/ | |
public function maybe_change_filename( $filename, $filename_raw ) { | |
if ( isset( $_POST['m_admin_page'] ) ) { | |
$filename = self::random_image_name(); | |
} | |
return $filename; | |
} | |
/** | |
* Just a function used to generate random image names. | |
* | |
* @return string | |
*/ | |
public static function random_image_name() { | |
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; | |
$result = ''; | |
for ( $i = 0; $i < 5; $i ++ ) { | |
$result .= $characters[ mt_rand( 0, 61 ) ]; | |
} | |
$result .= '_' . substr( md5( time() ), - 5 ); | |
$result .= '.jpg'; | |
return $result; | |
} | |
} | |
// Comment this out if you'd rather call it somewhere else. | |
new M_Custom_Uploads_Filename(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment