WordPress Media Uploader is pretty extendable, as we have learned in previous tutorials. This tutorial will be a short one and it will show you a way to add your own WordPress Media Uploader Custom Tab.
Why a Custom Tab?
You may wonder why you would ever need to have a custom tab in the WordPress Media Uploader. Tabs can help you organize the content you want to choose.
If for some reason, you just want to select images, why not have a tab that will show you only images in your WordPress Media Library?
Our Custom Tab
The custom tab that we are going to create will show 5 random items. This can then be used to select a lucky item. This is something just for fun.
Later on, I will also show you how to retrieve only images.
Enqueueing our Script
This is a standard procedure of enqueueing scripts or styles in WordPress.
It may seem a little confusing. Let me tell you what happens here.
- We assign the WordPress Media Library object to a variable
- Then, we save the current Media frame for the Post screen so that we can use it later
- We set a new Media frame for the Post screen by extending the saved (old) Media frame
- The method
initializeis the only one we change and to do that, we first call the old
- Inside that method, we add a new state using the
The main attribute here is the
library where a
wp.media.query is called. This query is actually the WordPress Query (
WP_Query). We are passing another parameter there. This parameter can be then used to check if we are on that tab and to modify the query.
The Lucky 5 Tab
Now that we have the script in place and that our Lucky 5 tab is there, we must now hook our function to modify the Query. We will need to hook our function on the filter
In this function, we are first checking if the query parameter lucky has been passed. If that is true, then we can move on and modify our query. We are setting a random order by using the parameter
orderby and the value
rand. We are also modifying the parameter
posts_per_page to retrieve only 5.
The Only Image Tab
If we don’t want the 5 random items, we can set the parameters of the query to retrieve only images. That is done like this:
Of course, you could change the query parameter we check there, but this is only for showing purposes.
This is the last tutorial of the series on Extending WordPress Media Uploader. Now, you have learned how to extend the WordPress Media Uploader in various ways. This knowledge can now help you to customize the experience of your clients even better.
Tutorials from this series:
If you have ever added a custom tab to the WordPress Media Uploader, please tell us in the comments below. Share your knowledge and provide others some useful examples of custom tabs.Become a Sponsor