Wordpress - Rename UPLOADS folder with custom WP_CONTENT_DIR
After digging around, I ended up with using upload_dir
filter.
Here is what I tried in functions.php
to change uploads
to media
. Hope it can help someone too :)
add_filter('upload_dir', function($uploads)
{
$custom = [];
foreach ($uploads as $key => $value) {
if ( false !== strpos($value, '/app/uploads') ) {
$custom[$key] = str_replace('/app/uploads', '/app/media', $value);
} else {
$custom[$key] = $value;
}
}
return $custom;
});
Many thanks to @gmazzap for the guidelines and the suggestion about upload_dir
filter!
If you look at the source of _wp_upload_dir
, you'll see:
if (defined('UPLOADS') && ! (is_multisite() && get_site_option('ms_files_rewriting'))) {
$dir = ABSPATH.UPLOADS;
$url = trailingslashit($siteurl).UPLOADS;
}
So UPLOADS
can only be used to define a foder relative to ABSPATH
, which I guess is /WordPress
folder in your setup.
In the same function, you can see that if get_option('upload_path')
and get_option('upload_url_path')
are empty, the path and the URL of uploads folder are set to, respectively, WP_CONTENT_DIR.'/uploads'
and WP_CONTENT_URL.'/uploads'
which should be perfectly fine for you, as long as you define WP_CONTENT_DIR
and WP_CONTENT_URL
like in OP.
If you don't define UPLOADS
at all and the uploads folder is still not resolved to /app/uploads
, very likely your database contains some value for 'upload_path'
and 'upload_url_path'
options.
You have 2 possibilities:
- delete those options
- use
"pre_option_{$option}"
filters to forceget_option()
to return something empty for those options (but notfalse
or the filters will be ignored).
For the second possibility the code could be something like this:
add_filter('pre_option_upload_path', '__return_empty_string');
add_filter('pre_option_upload_url_path', '__return_empty_string');
With the above code in place, and without any UPLOADS
constant defined, as long as you define WP_CONTENT_DIR
and WP_CONTENT_URL
, the uploads folder should be resolved correctly.
If that not happen, there must be something that acts on some filter, for instance upload_dir
.