Organize uploads by year, month and day

by Giri   Last Updated September 29, 2018 19:08 PM

As of now my uploaded files are organized by year and month. But I would like to organize them by year, month and day. I mean like this 2012/10/30/image goes here

PS: There is a plugin available to do this. But I don't want to use a plugin for this simple task. Thanks



Answers 3


Code based in other Answer of mine and this SO Answer.

It uses the post/page/cpt publish date to build the paths.
Note that $the_post->post_date_gmt is also available.

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;
}
brasofilo
brasofilo
October 31, 2012 15:33 PM

As far as I can tell, the filter 'upload_dir' is only called once in wp-includes\functions.php

I find this solution to be much simpler. It will place all uploads into the year/month/day directory for the date it is uploaded.

function upload_dir_filter($uploads){
    $day = date('d');
    $uploads['path'] .= '/' . $day;
    $uploads['url']  .= '/' . $day;
    return $uploads;
}
add_filter('upload_dir', 'upload_dir_filter');
Greenzilla
Greenzilla
December 16, 2015 21:15 PM

it is also possible to organize folders by hourly time?

year, month, day and hour

Marco
Marco
September 29, 2018 18:43 PM

Related Questions




front end post and uploads for custom post type

Updated April 25, 2018 14:08 PM

Create a duplicate media attachment post

Updated January 14, 2018 12:08 PM