Is there a way to specify the tab to display when the Media Uploader is displayed?

The following code will select a custom tab labeled Your Tab Name when launching the Media Library for the first time.

add_action( 'admin_footer-post-new.php', 'wpse_default_media_library_tab' );
add_action( 'admin_footer-post.php', 'wpse_default_media_library_tab' );
function wpse_default_media_library_tab() {
?>
<script type="text/javascript">
    var my_tab_has_been_activated = 0;
    (function($) {
        $(document).ready( function() {

            // http://wordpress-hackers.1065353.n5.nabble.com/JavaScript-events-on-media-popup-td42941.html
            $(document.body).on( 'click', '.insert-media', function( event ) {
                if ( 0 == my_tab_has_been_activated ) {

                    // Locates and activates media tab with label of search_text when the Media
                    // Library is initially opened.
                    var search_text = "Your Tab Name";

                    // http://stackoverflow.com/a/36054483/3059883
                    var $search_tab = $( ".media-menu-item" ).filter( function () {
                            return $( this ).text().toLowerCase().indexOf( search_text.toLowerCase() ) >= 0;
                    }).first(); // Returns the first element that matches the text. You can return the last one with .last()
                    $search_tab.trigger( 'click' );

                    my_tab_has_been_activated = 1;
                 }
            }); 

        });
    })(jQuery);
</script><?php
}

To customize the code for your tab, simply change the following line so that it matches the text for your tab’s menu label:

var search_text = "Your Tab Name"; // Change the text as needed.

This is not the prettiest solution, but it does work for me. It would be more elegant to do this via the wp.media API, but after quite a bit of effort, I wasn’t able to pull that off.

Custom Tabs Demo

For the sake of completeness, here is some basic demo code via this answer which shows how to create a custom media library tab. Note that this is the pre WordPress v3.5 way of doing things. Here’s an answer that deals with creating media tabs using the newer JS API.

add_filter( 'media_upload_tabs', 'media_upload_tabs__tab_slug' );
function media_upload_tabs__tab_slug( $_default_tabs ) {
    $newtab = array ( 'tab_slug' => 'Your Tab Name' );
    $tabs = array_merge( $_default_tabs, $newtab );

    return $tabs;
}

add_action( 'media_upload_tab_slug', 'media_upload_tab_slug__content' );
function media_upload_tab_slug__content() {
    wp_iframe( 'media_upload_tab_slug_content__iframe' );
}

function media_upload_tab_slug_content__iframe() {
    ?>
    <div>tab_slug: Add your content here.</div><?php
}

Leave a Comment