Change Upload Directory for Specific Files Types

Available Plugin GL Upload Dir

/*
 * Change Upload Directory for Specific Files Type
 * Only works in WordPress 3.3+
 */

function wpse47415_pre_upload( $file ) {
    add_filter( 'upload_dir', 'wpse47415_custom_upload_dir' );
    return $file;
}

function wpse47415_post_upload( $fileinfo ) {
    remove_filter( 'upload_dir', 'wpse47415_custom_upload_dir' );
    return $fileinfo;
}

function wpse47415_custom_upload_dir( $path ) {
    $extension = substr( strrchr( $_POST[ 'name' ], '.' ), 1 );

    if ( empty( $path[ 'error' ] ) ) {
        switch ( $extension ) {
            case 'pdf':
                $customdir = '/pdf';
                break;

            case 'doc':
                $customdir = '/doc';
                break;

            case 'zip':
                $customdir = '/zip';
                break;
        }
    } else {
        return $path;
    }

    $path[ 'path' ] = str_replace( $path[ 'subdir' ], '', $path[ 'path' ] ); //remove default subdir (year/month)
    $path[ 'url' ] = str_replace( $path[ 'subdir' ], '', $path[ 'url' ] );
    $path[ 'subdir' ] = $customdir;
    $path[ 'path' ] .= $customdir;
    $path[ 'url' ] .= $customdir;

    return $path;
}

add_filter( 'wp_handle_upload_prefilter', 'wpse47415_pre_upload' );
add_filter( 'wp_handle_upload', 'wpse47415_post_upload' );

Leave a Reply