Bug: Deleting file, then uploading same file again places file in an old month folder

Something you can try, but I haven’t tested it throughly, and you’ll need to do some QA to make sure it doesn’t ripple out and affect anything else. Explanation:

The function that returns paths to the upload directory is called wp_upload_dir(). It’s used in a bunch of places (and by a lot of plugins) to generate, er, a path to the upload dir. It accepts a parameter called time, which (when passed) will dictate which year/month gets used in the dir structure.

Unfortunately, when uploading from a post, there’s nowhere to filter this “time”. The function that does the uploading (called media_handle_upload(), I’m pretty sure), always uses the publish date of the post when media is being uploaded from a post edit screen. It only uses the current time if the upload isn’t associated with a post. No filters there.

But! The wp_upload_dir() function has a filter you can use, named “upload_dir”. It filters an array containing all the parts of the generated dir. One of the array items is named “subdir”, and it contains the year/month part of the path, if applicable. You can use this filter to check if the subdir portion is non-empty, and if it is, replace its value with the current year/month.

The gamble there is that you can’t tell the context in which wp_upload_dir is being called, and you’re betting that no other functions actually use the time parameter in a way that’d break. I took a quick look around the core, and the only place I see it used is in the function wp_upload_bits, and I’m not sure exactly what that’s for. In any case, I’d guess it only gets called on actual file uploads, so you’re probably good there. But you’ll want to test thoroughly with the plugins you have installed.

Code would look something like this:

    function wpsx_53067_filter_upload_dir($arr) {

        if(isset($arr['subdir']) && !empty($arr['subdir'])) {

            // The existing dir, for reference
            $old_dir = $arr['subdir'];

            // Your new dir (you could edit this to grab the current year/month)
            $new_dir="/any-new-dir-you-like";

            // Update the array. Need to update the subdir, path and url items (they all contain the full path)
            $arr['subdir'] = $new_dir;
            $arr['path'] = str_replace($old_dir, $new_dir, $arr['path']);
            $arr['url'] = str_replace($old_dir, $new_dir, $arr['url']);

        }

        return $arr;

    }
   add_filter('upload_dir', 'wpsx_53067_filter_upload_dir');