wordpress change upload directory for custom post type

add_filter('wp_handle_upload_prefilter', 'so_8519968_handle_upload_prefilter');
add_filter('wp_handle_upload', 'so_8519968_handle_upload');

function so_8519968_handle_upload_prefilter( $file )
{
add_filter('upload_dir', 'so_8519968_custom_upload_dir');
return $file;
}

function so_8519968_handle_upload( $fileinfo )
{
remove_filter('upload_dir', 'so_8519968_custom_upload_dir');
return $fileinfo;
}

function so_8519968_custom_upload_dir( $path )
{
// Check if uploading from inside a post/page/cpt - if not, default Upload folder is used
$use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
if( !empty( $path['error'] ) || $use_default_dir )
return $path;

// Check if correct post type
$the_post_type = get_post_type( $_REQUEST['post_id'] );
if( 'movies' != $the_post_type )
return $path;

$customdir = '/' . date( 'Y/m' );

//remove default subdir (year/month) and add custom dir INSIDE THE DEFAULT UPLOAD DIR
$path['path'] = str_replace( $path['subdir'], '/downloads' . $customdir, $path['path']);
$path['url'] = str_replace( $path['subdir'], '/downloads' . $customdir, $path['url']);

$path['subdir'] = $customdir;

return $path;
}

Đọc thêm
Thu Gọn