Dynamically change upload directory (1 post)

  1. hexagongirl
    Posted 3 years ago #

    I am creating a site where I need to restrict access to some uploads (docs/images) to logged-in users only.

    I've worked out how to dynamically change the upload folder based on the admin user adding the post to a 'members-only' category before doign the upload (I then restrict access to this '/protected' directory in .htaccess):

    add_filter('wp_handle_upload_prefilter', 'hex_pre_upload');
    add_filter('wp_handle_upload', 'hex_post_upload');
    function hex_pre_upload($file){
      foreach (get_categories() as $category)
       if ($category->slug == 'members-only') {
      	   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;
    function hex_post_upload($fileinfo){
    	foreach (get_categories() as $category)
       if ($category->slug == 'members-only') {
      	   remove_filter('upload_dir', 'hex_custom_upload_dir');
      return $fileinfo;

    But what I want to do is remove the dependancy on the user selecting the right category before upload, and rather give them a second media upload button specifically for protected uploads.

    This code creates the additional button:

    function hex_protected_media_button($context) {
      global $post;
    	$media_button_image = '../wp-admin/images/media-button.png?ver=20111005';
    	$media_button = ' %s' . '<a href="media-upload.php?post_id='.$post->ID.'&TB_iframe=1" class="thickbox"><img src="'.$media_button_image.'" /></a>';
    	return sprintf($context, $media_button);
    add_filter('media_buttons_context', 'hex_protected_media_button');

    But what I can't work out is how to tie the two pieces together, so that when the user clicks the 'protected' button, the upload directory for the media uploader is temporarily changed.

    Thanks for reading this far - any pointers greatly appreciated!

Topic Closed

This topic has been closed to new replies.

About this Topic


No tags yet.