Change upload directory on custom plugin page

After working on this for a bit and checking the GLOBALS variable for anything useful, it looks like the referring URL inside of the media modal is the same URL as my custom plugin page.

Using that and splitting it up a bit I was able to confirm that I am on the approrpriate page. I’m sure that there are other, more elegant solutions out there, but this is what I was able to come up with. I have tested and it seems to be working properly.

Here is my final solution :

    add_filter( 'admin_init' , 'check_if_we_should_change_upload_dir', 999 );
    function check_if_we_should_change_upload_dir() {   
            global $pagenow;
            $referrer = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '';
            if( $referrer != '' ) {
                $explode_1 = explode( 'page=" , $referrer );
                if( isset( $explode_1[1] ) ) {
                    $referring_page = explode( "&id=' , $explode_1[1] );
                    if( isset( $referring_page[0] ) && $referring_page[0] == 'custom-plugin-page' && ( 'async-upload.php' == $pagenow || 'media-upload.php' == $pagenow ) ) {
                        add_filter( 'upload_dir', 'alter_the_upload_dir' );
                    }
                }
            }
       }


  function alter_the_upload_dir( $upload ) {
        $upload['subdir'] = '/custom-directory' . $upload['subdir'];
        $upload['path'] = $upload['basedir'] . $upload['subdir'];
        $upload['url']  = $upload['baseurl'] . $upload['subdir'];
        return $upload;
    }

If anyone has any better solutions to checking, I am all ears!

Evan

Leave a Comment