I have a custom media upload button (in the standard post edit page, alongside the standard media upload button), and need to change the upload directory dynamically if this button is clicked – using add_filter(‘wp_handle_upload_prefilter’, ‘my_function’).
This post & answer: Conditional add_filter? seem to give the solution, but for some reason don’t work for me – the additional parameter ‘hexProtected’ is not set & so add_filter is not called.
My code is below… am I doing something stupid or does the solution posted not work?!
<?php
/* Custom Upload Directory for protected posts */
function hex_protected_media_button($context) {
global $post;
$media_button_image = 'http://www.example.com/wp-admin/images/media-button.png?ver=20111005';
$media_button = ' %s' . '<a href="media-upload.php?post_id='.$post->ID.'&TB_iframe=1&hexProtected=1" class="thickbox"><img src="'.$media_button_image.'" /></a>';
return sprintf($context, $media_button);
}
add_filter('media_buttons_context', 'hex_protected_media_button');
add_filter('wp_handle_upload_prefilter', 'hex_pre_upload');
add_filter('wp_handle_upload', 'hex_post_upload');
function hex_pre_upload($file){
if (isset($_GET['hexProtected'])) {
add_filter('upload_dir', 'hex_custom_upload_dir');
}
return $file;
}
function hex_custom_upload_dir($path){
if(!empty($path['error'])) { return $path; } //error; do nothing.
$path['path'] = str_replace($path['subdir'], '/protected'.$path['subdir'], $path['path']);
$path['url'] = str_replace($path['subdir'], '/protected'.$path['subdir'], $path['url']);
$path['subdir'] = '/protected';
return $path;
}
?>
I know it’s been a while, but I wanted to offer a solution, if only for those who come across this question via Google.
The issue is with the order of the parameters in the query string when you build the URL for the media uploader. My experience is that any parameters that come after ‘TB_iframe=1’ are ignored, so you want to put your custom values before this. I haven’t seen this documented (and haven’t explored core to see why the parameters are handled this way), but can’t think of any good reason for it–I probably spent an hour tearing my hair out before I discovered the issue.
I also haven’t tried this in 3.5 yet. With all the changes to the media uploader it’s possible that this has been addressed.