WordPress: Get path to uploads folders

Working with other people’s code can be quite frustrating at times, because coders, even the best, sometimes make unwarranted assumptions.

Among these assumptions are the locations of certain folders. Often people will hard-code a path wp-content. While this is a convention, this is not a universal. This value can be changed, and many do simply as a small added defense against bots.

Along these lines is also hard-coding a path to the uploads folder.

WordPress allows us to access the path programatically using wp_upload_dir() as such

$path = wp_upload_dir();
echo $path['url'];

Sometimes, though, one doesn’t necessarily want that extra line. I prefer to keep a minimum of code in my templates, when possible. Here’s my small little work-around. Just copy and paste the following code into you functions.php file, or where ever you please.

Call it as such get_uploads_dir('baseurl');

See in-line comments for a reminder of which path you would like it to return.

function get_uploads_dir( $arg ) {
	/*
	 * A small utility to make these paths available in a one-liner
	 *
	 * [path]   => /home/example.com/wordpress/wpcontent/uploads/2008/11
	 * [url]    => http://www.example.com/wordpress/wp-content/uploads/2008/11
	 * [subdir] => /2008/11
	 * [basedir]=> /home/example.com/wordpress/wp-content/uploads
	 * [baseurl]=> http://www.example.com/wordpress/wp-content/uploads
	 * [error]  =>
	 * */
	$image_path = wp_upload_dir();
	switch ( $arg ) {
		case 'path':
			$str = $image_path['path'];
			break;
		case 'url':
			$str = $image_path['url'];
			break;
		case 'subdir':
			$str = $image_path['subdir'];
			break;
		case 'basedir':
			$str = $image_path['basedir'];;
			break;
		case 'baseurl':
			$str = $image_path['baseurl'];
			break;
		default:
			$str = '';
	}

	return $str;
}

For more details on wp_upload_dir();

wp_upload_dir()