Make Upload the Default Media Tab for WordPress

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

When I click the “Add Media” button in the WordPress 4.1 editor …

add media button

add media button

I want the “Upload Files” tab to be enabled by default without me needing to click to select that tab…

want upload files be the default tab

These are the two media tabs

This is not a simple thing to do.  So this is going to be an advanced tutorial. But here it is.

1. First we need to add jQuery javascript to the WordPress admin.  We use the admin-script.js as described in our previous tutorial.

We add this to theme’s functions.php…

admin_init hook

admin_init hook

Then in “js/admin-script.js” within the theme’s directory, we add …

using jQuery in WordPress

using jQuery in WordPress

This is how we set up jQuery’s document ready event handler in WordPress.  If all is well, check that you get “at admin script” in console when WP dashboard is loaded.

2.  With the browser inspector, we see that the “Add Media” button has id of “insert-media-button”.  When this button is clicked, we want to poll to see when the Media tabs show up.

set up setInterval

set up setInterval

We do this by using Javascript’s setInterval to call our pollMediaTab() function every 100 milliseconds.  We have to poll to see when the media tabs come up, because they may not always come up instantaneously after the “Add Media” button is clicked.

The setInterval handle is saved to myTimeout variable so that we can cancel our interval later.  The iPolled variable is set to 0 and incremented every time we poll.  We will define the myTimeout and iPolled variable outside in a global space here …

set up variables

set up variables

And we define pollMediaTab() function is defined as follows …

The full script

The full script

The “Upload Files” is the first tab and can be jQuery selected by “.media-router a:first-child”.   When this selector length is greater than 0, that means that tab has appeared and is available for us to click it.  We click it with …

$(‘.media-router a:first-child’).click();

After the tab is clicked, we clear the interval.

But if we have polled more than 5 times (iPolled > 5) without the tab appearing, something must have failed and give up by clearing the interval.

That so do it.