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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
<?php
namespace SIW;
class Upload_Subdir {
public static function init() {
$self = new self();
add_filter( 'wp_handle_sideload_prefilter', [ $self, 'add_upload_subdir_filter'] );
add_filter( 'wp_handle_upload_prefilter', [ $self, 'add_upload_subdir_filter'] );
add_filter( 'wp_handle_upload', [ $self, 'remove_upload_subdir_filter'] );
}
public function add_upload_subdir_filter( array $file ) {
add_filter( 'upload_dir', [ $this, 'set_upload_subdir'] );
return $file;
}
public function remove_upload_subdir_filter( array $fileinfo ) {
remove_filter( 'upload_dir', [ $this, 'set_upload_subdir'] );
return $fileinfo;
}
public function set_upload_subdir( array $path ) {
if ( ! empty( $path['error'] ) ) {
return $path;
}
$subdir =
$this->get_extension_subdir() ??
$this->get_post_type_subdir() ??
null;
$subdir = apply_filters( 'siw_upload_subdir', $subdir );
if ( null !== $subdir ) {
$subdir = '/'. $subdir;
$path['path'] = str_replace( $path['subdir'], '', $path['path'] );
$path['url'] = str_replace( $path['subdir'], '', $path['url'] );
$path['subdir'] = $subdir;
$path['path'] .= $subdir;
$path['url'] .= $subdir;
}
return $path;
}
protected function get_post_type_subdir() {
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ): null;
if ( null === $post_id ) {
return null;
}
$post_type = get_post_type( $post_id );
$cpt_upload_subdirs = [
'siw_tm_country' => 'op-maat',
'siw_tm_story' => 'ervaringen',
];
$cpt_upload_subdirs = apply_filters( 'siw_cpt_upload_subdirs', $cpt_upload_subdirs );
return $cpt_upload_subdirs[ $post_type ] ?? null;
}
protected function get_extension_subdir() {
$name = isset( $_POST['name'] ) ? sanitize_title( $_POST['name'] ): null;
if ( null === $name ) {
return null;
}
$extension = pathinfo( $name, PATHINFO_EXTENSION );
$extension_subdirs = [
'pdf' => 'documenten',
];
return $extension_subdirs[ $extension ] ?? null;
}
}