Recently we had a client that wanted to make sure all of the files in one of their galleries was in a specific directory instead of the default upload/year/month directory.
Here is a simple function to make sure that happens, including updating all previous files uploaded to that gallery.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/** * Update the file path of Custom files so that they always are located in the Custom folder */ add_action('acf/save_post', 'jb_update_gallery_fields', 1); function jb_update_gallery_fields( $post_id ) { // specific new field value $gallery = $_POST['acf']['field_234567890dfghj']; if(! empty($gallery)){ $folder = sanitize_file_name( get_the_title($post_id) ); $model_dir = '/Custom/'.$folder.'/'; $uploads = wp_upload_dir(); $path = $uploads['basedir'] . $model_dir; if (! file_exists($path)) { mkdir($path, 0777, true); } foreach($gallery as $attachment_id){ $fullsize_path = get_attached_file( $attachment_id ); //is this attachment in the Custom folder? if (strpos($fullsize_path, 'Custom') === false) { $new_filepath = $path.basename($fullsize_path); //Not in the Custom folder rename($fullsize_path, $new_filepath); update_attached_file( $attachment_id, $new_filepath ); } } } } |