I'm writing a plugin that, as part of its functionality, uploads custom fonts. I'm using the new-since-Wordpress-3.5 media uploader & API.
I've read dozens of tutorials on how to change the upload path but am having problems making it work. Currently, it places the font files in the correct directory within the plugin, but throws a Wordpress error during the upload ('An error occurred in the upload. Please try again later.'), and, initially, doesn't show the uploaded file in the library. If you reload the plugin page & reopen the uploader, the file then shows up in the library, but the URL field is incorrect.
I've defined my plugin path & URL as constants in the main file:
if ( !defined( 'MYPLUGIN_DIR' ) ) {
define('MYPLUGIN_DIR', plugin_dir_path(__FILE__));
};
if ( !defined( 'MYPLUGIN_URL' ) ) {
define('MYPLUGIN_URL', p`lugin_dir_url(__FILE__));
};
Then, in the options file, I have:
add_filter('wp_handle_upload_prefilter', 'myplugin_upload_prefilter');
add_filter('wp_handle_upload', 'myplugin_handle_upload');
// filter the upload_dir hook
function myplugin_upload_prefilter( $file ) {
add_filter('upload_dir', 'myplugin_upload_dir');
return $file;
}
// unset the filter & return upload path to default
function myplugin_handle_upload( $fileinfo ) {
remove_filter('upload_dir', 'myplugin_upload_dir');
return $fileinfo;
}
function myplugin_upload_dir($path) {
$fontdir = 'assets/fonts'; // desired directory relative to plugin root
$path['path'] = MYPLUGIN_DIR . $fontdir;
$path['url'] = MYPLUGIN_URL . $fontdir;
$path['subdir'] = $fontdir;
$path['basedir'] = MYPLUGIN_DIR;
$path['baseurl'] = MYPLUGIN_URL;
return $path; // altered
}
An example of a malformed URL in the library router view is http://127.0.0.1/webroot/wp-content/uploads//Applications/MAMPSERVER-OR-WHATEVER/www/webroot/wp-content/plugins/myplugin/assets/fonts/myfont.woff
. The URL should be http://127.0.0.1/webroot/wp-content/plugins/myplugin/assets/fonts/myfont.woff
. Note the double slash after 'uploads'; I tried untrailingslashit
to at least remove that, but it didn't work.
- Why does this code initially throw an error?
- Why does the library item not appear initially, but then appear on page reload & reopening the modal?
- How to fix wrong URL?
A separate, but related issue, is ensuring the path is altered only when media is uploaded from the plugin settings page, but I will post a separate question on that.