Extending wp.media.model, query media from different blog on network and refresh view

I’m trying to extend the new wp.media.model to allow users to be able to choose any blog across the network and pull down the associated media library into the library content view.

In the old thickbox we just called switch_to_blog() and refreshed the thickbox.

Read More

I would like to stay within the new backbone.js media-views and media-models (open to other suggestions) but I’m having trouble getting wp.media.query() to return the results from the correct blog. I’m calling switch_to_blog() using the wp.media.ajax method and the correct global variables are being set. The result of the query variable below is an object of attachments for the original blog not the switched to blog.

javascript:

/*global blogs */ //Object of network blogs passed via wp_localize_script
(function ($) {
    "use strict"; // jshint ;_;

    var current = blogs['current_blog'];
    var Blogs = blogs['UserBlogs'];

    $(function() {
        var media = wp.media.editor.add('content');
        media.on('open', function() {
            var html = $("<select>", {name:'blog_id', id: 'blog_id'});
            $.each(Blogs, function (index, blog) {
                if( 1 == index ) { return; }
                html.append($("<option>", {value:blog.userblog_id, html:blog.domain}).prop({ selected: blog.userblog_id == current}));
            });
        $(".attachment-filters").after(html);

        $("select#blog_id").change(function () {
            var str = "";
            $("select#blog_id option:selected").each(function () {
                str += $(this).val();
                var options = {
                    type: 'POST',
                    url: ajaxurl,
                    data: {
                        blog: str
                    }
                };
                wp.media.ajax('switch_blog', options );
                var query = wp.media.query();
                console.log(query);
            });
        })
    });
});
}(jQuery));

PHP:

public static function _switch_blog() {
    global $blog_id;
    $current = $blog_id;
    $blog = isset( $_POST['blog'] ) ? intval( $_POST['blog'] ) : false;
    $result = false;
    if ( (bool)$blog )
        $result = switch_to_blog( (int)$blog );
       if ( $result )
           echo json_encode( array( 'success' => $result, 'response' => 'Switched from: '.$current. ' to '.$blog_id ) );

    exit;
}

Related posts

Leave a Reply