1

I'm using WordPress media upload through wp_enqueue_media(); to upload media. It works perfect.

But,

  • I'm using multisite.
  • Media upload is available on all sub domains.
  • If someone upload image from sub-domain1, sub-domain-2 etc then it should be uploaded into main domain media library.

I have tried switch_to_blog() & restore_current_blog() but it not works. Check below snippets.

Working Demo

1) Shortcode - [my-media]

add_shortcode( 'my-media', 'my_media_frontend_shortcode' );
function my_media_frontend_shortcode( $args ) {
    return '<button id="my-media-upload" class="button button-primary">Upload</button>';
}

2) Enqueue media.js

add_action( 'wp_enqueue_scripts', 'my_media_enqueue_scripts' );
function my_media_enqueue_scripts() {
    wp_enqueue_media();
    wp_enqueue_script(
        'my-media',
        plugins_url( '/', __FILE__ ) . 'js/media.js',
        array( 'jquery' )
    );
}

3) js/media.js

(function($) {
    $(document).ready( function() {

        $( '#my-media-upload' ).on( 'click', function( event ) {
            event.preventDefault();

           var file_frame = wp.media({
                title: 'Media',
                button: {
                    text: 'Upload Media',
                },
                multiple: false
            });

            file_frame.on( 'select', function() {
                var attachment = file_frame.state().get('selection').first().toJSON();

                console.log( attachment ); // Works
                console.log( attachment.url ); // Works
            });

            file_frame.open();
        });
    });
})(jQuery);

Trying to use switch_to_blog()

I have used switch_to_blog() & restore_current_blog() to use MAIN site to upload all media. But, It not works.

add_action( 'wp_enqueue_scripts', 'my_media_enqueue_scripts' );
function my_media_enqueue_scripts() {

    // Switch to blog 1
    switch_to_blog( 1 );

    wp_enqueue_media();
    wp_enqueue_script(
        'my-media',
        plugins_url( '/', __FILE__ ) . 'js/media.js',
        array( 'jquery' )
    );

    // Restore to current blog.
    restore_current_blog();
}

After digging I found ajax_query_attachments_args is used in AJAX hook wp_ajax_query_attachments. I use it and it works.

But break the sub domain media library. It does not restore the domain.

add_filter( 'ajax_query_attachments_args', 'my_site_switch_to_blog' );
function my_site_switch_to_blog( $args ) {

    // Switch to Blog 1.
    switch_to_blog( 1 );
    return $args;
}

Is there any way to achieve this with Action/Filter?

Your Answer

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

Browse other questions tagged or ask your own question.