Customizing the upload directory programatically

Mods and Stuff for WordPress
Post Reply
User avatar
syntax
Site Admin
Posts: 54
Joined: Tue Jan 06, 2009 9:25 pm

Customizing the upload directory programatically

Post by syntax » Wed Dec 17, 2014 5:47 pm

The code below first puts the page hierarchy of a page after the base path of the upload directory. The second parts adds a the day of the month to the end of the path, but only for pages under a certain parent ('Meeting Information').

Code: Select all

//customize upload dir
add_filter('upload_dir', 'custom_upload_dir');

function custom_upload_dir( $param ){
	if ( isset( $_REQUEST['post_id'] ) ) {
		$post_id = absint( $_REQUEST['post_id'] );
		$post = get_post($post_id);
	}
	if (!empty($post_id) && !empty($post) && get_post_type($post) == 'page') {
		$is_board_meeting = FALSE;
		$parent_id  = $post->post_parent;
		$breadcrumbs = array();
		while ($parent_id) {
		  $page = get_page($parent_id);
		  $breadcrumbs[] = sanitize_file_name(get_the_title($page->ID));
		  $parent_id = $page->post_parent;
		  if ($breadcrumbs[count($breadcrumbs)] == 'Meeting Information') { $is_board_meeting = TRUE; }
		}
		if (!empty($breadcrumbs)) {
			$breadcrumbs = array_reverse($breadcrumbs);
			$path_to_insert = implode("/", $breadcrumbs);

			$new_path = $param['basedir'] . '\\' . $path_to_insert . substr($param['path'], strlen($param['basedir']));
			$new_url = $param['baseurl'] . '/' . $path_to_insert . substr($param['url'], strlen($param['baseurl']));
			
			$param['path'] = $new_path;
			$param['url'] = $new_url;
		}
		
		if ($is_board_meeting) {
			$time = get_the_time('Y-m-d', $post);
			if (strlen($time) == 10) {
				//1981-06-01
				//0123456789
				$y = substr( $time, 0, 4 );
				$m = substr( $time, 5, 2 );
				$d = substr( $time, 8, 2 );
				if (strlen($d) == 2 && substr(strrev($param['path']), 0, 7) == strrev($y.'/'.$m)) {
					$add_to_dir = "/$d";
					$param['path'] = $param['path'] . $add_to_dir;
					$param['url'] = $param['url'] . $add_to_dir;
				}
			}
		}
	}
    return $param;
}

Post Reply