'WordPress change upload_dir for specific files to root dont work
I would like to place PDF files uploaded via the media library in a separate folder in the root directory. I have already developed a filter for this and the files are stored correctly. However, the permalink of the file is wrong and contains the URL as well as the path.
I use the following source code (excerpt)
$customdir = 'custom-uploads';
$path['path'] = wp_normalize_path( ABSPATH . $customdir );
$path['url'] = home_url( '/' . $customdir );
$path['subdir'] = "/" . $customdir;
$path['basedir'] = $path['path'];
$path['baseurl'] = $path['url'];
The object (path) before the filter looks like this:
[22-Apr-2022 13:59:12 UTC] Array
(
[path] => /var/www/srv/apps/apptest01/wp-content/uploads/2022/04
[url] => https://example.com/wp-content/uploads/2022/04
[subdir] => /2022/04
[basedir] => /var/www/srv/apps/apptest01/wp-content/uploads
[baseurl] => https://example.com/wp-content/uploads
[error] =>
)
Before the return:
[22-Apr-2022 13:59:12 UTC] Array
(
[path] => /var/www/srv/apps/apptest01/custom-uploads
[url] => https://example.com/custom-uploads
[subdir] => /custom-uploads
[basedir] => /var/www/srv/apps/apptest01/custom-uploads
[baseurl] => https://example.com/custom-uploads
[error] =>
)
But the permalink of the file is now as follows:
https://example.com/wp-content/uploads//var/www/srv/apps/apptest01/custom-uploads/file.pdf
Can anyone help me with this? Thanks in advance!
Solution 1:[1]
You can register a filter for the wp_get_attachment_url
function to right the URL composed by Wordpress.
/**
* Filters the attachment URL.
*
* @param string $url URL for the given attachment.
* @param int $attachment_id Attachment post ID.
*/
function right_composed_attachment_url( $url, $attachment_id ) {
$wrong_base_url = 'https://example.com/wp-content/uploads//var/www/srv/apps/apptest01/custom-uploads';
$uploads = wp_get_upload_dir();
$correct_base_url = $uploads['baseurl'];
$custom_upload_has_wrong_base_url = strpos( $c, $wrong_base_url ) !== false;
if ( $custom_upload_has_wrong_base_url ) {
return str_replace( $wrong_base_url, $correct_base_url, $url );
}
return $url;
}
add_filter( 'wp_get_attachment_url', 'right_composed_attachment_url' );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |