Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.