Skip to content

Instantly share code, notes, and snippets.

@rahilwazir
Last active July 13, 2020 21:10
Show Gist options
  • Save rahilwazir/7476ae318de93128d1cf19fb49aa3006 to your computer and use it in GitHub Desktop.
Save rahilwazir/7476ae318de93128d1cf19fb49aa3006 to your computer and use it in GitHub Desktop.
Change upload directory, async upload, handle upload in WordPress

Change upload directory

// Grabbed from edd plugin
function set_upload_dir() {

	// Override the year / month being based on the post publication date, if year/month organization is enabled
	if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
		// Generate the yearly and monthly dirs
		$time = current_time( 'mysql' );
		$y = substr( $time, 0, 4 );
		$m = substr( $time, 5, 2 );
		$upload['subdir'] = "/$y/$m";
	}

	$upload['subdir'] = '/YOUR_CUSTOM_DIR' . $upload['subdir'];
	$upload['path']   = $upload['basedir'] . $upload['subdir'];
	$upload['url']    = $upload['baseurl'] . $upload['subdir'];
	return $upload;
}

function change_uploads_dir() {
	global $pagenow;
	
	// Add any conditional logic on when to change directory
	
	add_filter( 'upload_dir', 'set_upload_dir' );
}
add_action( 'admin_init', 'edd_change_downloads_upload_dir', 999 );

Async Uploads

async-uploads.php file lives in wp-admin/async-upload.php

File Handling

Function media_handle_upload handles every file uploads, insert attachment and generate attachment metadata.

Function wp_handle_upload move file to approriate directory and return file attributes.

Similar functions media_handle_sideload and wp_handle_sideload to handle image upload from another server. See here for more info

Tip: You can download a URL with download_url function.

Filter hook wp_handle_upload runs when the file uploads successfully, you can use this to manipulate or change attributes of the uploaded file.

Usage:

add_filter( 'wp_handle_upload', function( $upload, $context ) {
    /**
     * @param array $upload {
	 *     Array of upload data.
	 *
	 *     @type string $file Filename of the newly-uploaded file.
	 *     @type string $url  URL of the uploaded file.
	 *     @type string $type File type.
	 * }
	 *
	 * @param string $context The type of upload action. Values include 'upload' or 'sideload'.
	 *
     */
     
     // Compress the file in .ZIP and return it's attributes assigning to `$uploads` variable.
     
     return $uploads;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment