I am using WordPress Media Library in my plugin in the backend. How to change the upload path for it dynamically? Can it be done during the enqueue, or when creating it in JavaScript?

I am using wp_enqueue_media() in admin_enqueue_scripts action, and later creating the media frame in Javascript using wp.media.

I’ve managed to change the directory when uploading using plupload_default_params filter, but I don’t know how to hook into the query-attachments action that queries the files into the library.

Update: After hours of tinkering I gave up and I went with a different solution. I am adding a new setting on plugin’s edit page and resetting it otherwise. This way I can access the option in ajax calls.

function change_upload_dir( $args ) {
        $user_id = get_current_user_id();
        $form = false;
        if( defined('DOING_AJAX') && DOING_AJAX ) {
            $form = get_option( 'test_edit_' . $user_id );
        }
        if($form || isset($_GET['type']) || isset($_POST['subfolder'])) {
            // change upload path 

And in the plugin construct:

    if( !(defined('DOING_AJAX') && DOING_AJAX) 
       && false === strpos($_SERVER['REQUEST_URI'], 'wp-content') ) {
        $edit = get_option( 'test_edit_' . get_current_user_id() );
        if ( $edit && $edit != '' ) {
            update_option( 'test_edit_' . get_current_user_id(), '' );
        }
    }

This works fine, unless the user opens a new tab and the setting gets reset.
It’s fine for now, but I’d really like to know if there is an easier way to do that.

2 s
2

Might wanna look at

wp_upload_dir()

In definition there is a hook upload_dir, you can use that to change path.

Haven’t tried or tested it, but you can give it a try.

Leave a Reply

Your email address will not be published. Required fields are marked *