Upload specific images to specific folder

In your answer you said that desired path is something like

wp-content\uploads\state-name\destination\

where state-name is a taxonomy term and destination is the slug of one destination CPT.
Last thing is not clear from your question, but it seems so, let me know if I’m wrong).

So, I suggest you this workflow:

Add a destination post -> assign a state term -> after that, upload the image using the media uploader from the destination post just created.

Doing so, we can retrieve the destination ID for current attachment (passed to media uploader as $_GET['post_id']), than retrieve the assigned state term, and finally set the folder using the 'upload_dir' filter.

Something easy:

add_filter('upload_dir', 'set_destination_folder', 999);

function set_destination_folder ( $upload_data ) {  

  if ( ! isset( $_REQUEST['post_id']) )
    return $upload_data;
  $destination = get_post( $_REQUEST['post_id'] );
  if ( empty($destination) || $destination->post_type != 'destinations' )
    return $upload_data;
  $states = get_the_terms($_REQUEST['post_id'], 'states');
  if ( empty($states) || ! is_array($states) ) {
    $subdir="/destinations/" . $destination->post_name;
  } else {
    $subdir="https://wordpress.stackexchange.com/" . array_shift($states)->slug . '/destinations/' . $destination->post_name;
  }
  $dir = $upload_data['basedir'] . $subdir;
  $url = $upload_data['baseurl'] . $subdir;
  return wp_parse_args(array('path'=>$dir, 'url'=>$url, 'subdir'=>$subdir), $upload_data);

}

In this way, when you upload images from a destination post, if the destination post as a state assigned (as taxonomy term) the image will uploaded in the folder

wp-content/{$state_slug}/destinations/{$destination_slug}/

if the destination post has no state assigned, the image will be saved in the folder

wp-content/destinations/{$destination_slug}/

If more states are assigned to destination, the first state is taken.

Note that this code assume the cpt name for destinations is, 'destinations' and the taxonomy name for states is 'states'.

Leave a Comment