Skip to content

Instantly share code, notes, and snippets.

@davidsword
Last active September 20, 2019 04:18
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 davidsword/44ef2090f2471f30abe1ed475c1f583e to your computer and use it in GitHub Desktop.
Save davidsword/44ef2090f2471f30abe1ed475c1f583e to your computer and use it in GitHub Desktop.
WordPress - force a specific /YYYY/MM folder for media uploads.
<?php
const FORCE_UPLOAD_DIR_SUBDIR_TO = '/1990/08'; // MUST be "/YYYY/MM" format.
/**
* Force uploads to land in a specific /YYYY/MM folder.
*
* @param array $uploads information about the upload directory
* @see https://github.com/WordPress/WordPress/blob/2b92bcab85cecd819596b79b0b52f44aa4dfaffa/wp-includes/functions.php#L2223-L2239
* @return array
*/
function force_custom_upload_dir_subdir( $uploads ) {
if ( ! get_option( 'uploads_use_yearmonth_folders' ) ) {
return $uploads;
}
// in case some weird subdir path is prepended, extract the date.
preg_match( "(\/(19|20)\d{2}\/(0|1)\d{1})", $uploads['subdir'], $current_subdir_date );
if ( $current_subdir_date[0] ) {
foreach ( [ 'subdir', 'path', 'url' ] as $k ) {
$uploads[$k] = str_replace( $current_subdir_date[0], FORCE_UPLOAD_DIR_SUBDIR_TO, $uploads[$k] );
}
}
return $uploads;
}
add_filter( 'upload_dir', 'force_custom_upload_dir_subdir' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment