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;
}
?>