基于代码的其他Answer of mine 还有这个SO Answer.
它使用post/page/cpt发布日期来构建路径<请注意$the_post->post_date_gmt
也可用。
add_filter(\'wp_handle_upload_prefilter\', \'wpse_70946_handle_upload_prefilter\');
add_filter(\'wp_handle_upload\', \'wpse_70946_handle_upload\');
function wpse_70946_handle_upload_prefilter( $file )
{
add_filter(\'upload_dir\', \'wpse_70946_custom_upload_dir\');
return $file;
}
function wpse_70946_handle_upload( $fileinfo )
{
remove_filter(\'upload_dir\', \'wpse_70946_custom_upload_dir\');
return $fileinfo;
}
function wpse_70946_custom_upload_dir($path)
{
/*
* Determines 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; // Error: not uploading from a post/page/cpt
$the_post = get_post( $_REQUEST[\'post_id\'] );
$y = date( \'Y\', strtotime( $the_post->post_date ) );
$m = date( \'m\', strtotime( $the_post->post_date ) );
$d = date( \'d\', strtotime( $the_post->post_date ) );
$customdir = \'/\' . $y . \'/\' . $m . \'/\' . $d;
$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;
}