2

I want to have two different paths for different files.

For example, I have all .zip and image files all in the same locations.

What I am wanting to the have images in one path (eg. wp-content/uploads/images/)

And all the zip files within another location/path (eg. wp-content/uploads/products/)

But what I am needing is when I add either in the media library when posting a new post for them to be entered/uploaded into the correct paths automatically.

How can I do this and is this possible?

0

Change upload directory for PDF Files seems to be a good stepping stone forward.

Although untested, looking at the code my adaptation would be along the lines of...

<?php

    add_filter('wp_handle_upload_prefilter', 'custom_media_library_pre_upload');
    add_filter('wp_handle_upload', 'custom_media_library_post_upload');

    function custom_media_library_pre_upload($file){
        add_filter('upload_dir', 'custom_media_library_custom_upload_dir');
        return $file;
    }

    function custom_media_library_post_upload($fileinfo){
        remove_filter('upload_dir', 'custom_media_library_custom_upload_dir');
        return $fileinfo;
    }

    function custom_media_library_custom_upload_dir($path){    
        $extension = substr(strrchr($_POST['name'],'.'),1);
        if ( !empty( $path['error'] ) ||  $extension != 'zip' ) 
        {
            return $path; 
        } //error or other filetype; do nothing. 

        elseif ( $extension = 'zip' )
        {
            $customdir = '/products';
        }
        elseif ( $extension = 'jpg' || $extension = 'jpeg' || $extension = 'gif' || $extension = 'png')
        {
            $customdir = '/images';
        }

        $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;
    }

This I would stick in the functions.php of your theme or in a relevant theme file - not in the wordpress core as you will lose it when you update!

You can also improve on my code by sticking matches in an array and comparing that, just did it this way for simplicity. An example could be...

$imagetypes = array( 'jpg', 'jpeg', 'gif', 'png', 'etc');
if ( in_array( $extension, $imagetypes ) ) 
{
    $customdir = '/images'; 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.