WordPress allowed me to get a better job & better projects in just a Year. I will give you tips, tricks and guide you into WordPress development so you can get more income. Sign up to my 7-day email course!
Galleries are an awesome way to show simple pictures in your posts. In this tutorial we will create a WordPress gallery that will show on the post on which we create it. We will also be able to decide the order of the images in our gallery.
The gallery will be attached to a single post so we will have to create a metabox for each post in the admin area where we will insert the gallery images. Interested? Let’s begin:)
All the code you find here can be used in any of your projects both personal and commercial.
We will make a class to handle our WordPress gallery (saving images, loading images, rendering images) and we will also create a class that could be a factory class which will create all the registered galleries. By doing that, we could have two or more galleries on each post. By using the OOP approach you can extend the initial class for the WordPress Gallery and create different gallery rendering.
If you want to see what we are going to build, you have a video at the bottom of this article. Click here to see it.
First, we will create our class that will handle the creation of the metabox and the rendering of the gallery.
In our constructor method we are assigning passed parameters to our attributes. If the title is empty, we will create it from the ID by capitalizing the first character. We do also check if the passed context and priority values are valid. Only if they are valid we will set them. I they are not valid, they will remain with the default value.
At the end of our constructor method we hook two of our methods to actions (one to add the metabox and one to save the metabox values). Let’s first define our method for adding the metabox:
We are defining possible post types on which our metabox will render. The post types can be easily extended using a general filter for the galleries or using a dynamic filter that can be used to specifically target only one metabox.
If the post type we are editing in the admin area matches the ones that are available to that metabox, we will add the metabox. Here we are using another method called render_meta_box_content. This method is used to display the metabox and all the information inside it. Let’s define that now.
Basically, we are generating a hidden WordPress Nonce field so that we can check on that before saving the data to make it more secure. After that we are getting the image IDs we have saved for that gallery. We use PHP function explode to generate an array from the provided string of image IDs. We check if there are any images and if there are, then we create a LI element with the image inside it for every image.
The HTML inside the LI element and the LI element alone are the same as provided in WordPress Media Library Modal. I decided to use that so that I can mimic the same style used in that modal. At the end of this method we render a button that will be used to open the WordPress Media Library so that we can choose between the images.
Now that we have our metabox output defined, we can focus on that second method in our constructor method. Remember it? The method name is save:
This is a generic save method since we first check for the nonce. If there is a nonce we verify it, if not we don’t save anything. If there is a nonce, then we are verifying it. If our nonce if verified we do check it is not an autosave and also if the user has the permission to edit the content.
Once everything is true and valid we are getting the posted data from our metabox (look at the hidden input we have set in the method render_meta_box_content – we are using that name). We are also sanitizing the field to remove any harmful data. The last thing, we are saving the metabox data (image IDs) in the post meta by using the dynamic meta key constructed from the metabox ID.
The last thing we have to do inside this class is to define a rendering method. This rendering method will be called inside our factory class. The method will receive the parameter $content which will contain the posts’ content and all other filtered content (if any). We will have to add our gallery inside that content and return it.
We have our main WordPress gallery class defined. By using a factory we can easily set more than one gallery on a post or similar. We could define several galleries and by using our dynamic filters, we can decide which gallery to show on which post type. This factory will create our galleries and also it will enqueue any script or style that is needed for our galleries.
We will enqueue only admin script and style so that our metabox galleries are render as intended. The front side will be handled by your theme or another plugin such as Jetpack so I will leave you decide how to style your galleries.
As with any class, we first define our attributes:
In our constructor method we hook the method do different actions and one filter. First we hook into the action init to get all the galleries that were added via our filter that we will define in the method collect_galleries. Next step is to enqueue all the scripts and styles that are needed for our galleries to work in the admin area.
After that we hook into the action admin_init so that we are sure that the metabox is created only in the admin area. The only filter into which we hook our method is the filter the_content where we will render galleries.
We are enqueueing our scripts and styles using the URL as if we are using a plugin. If you are using this code in your theme, then you should use the method get_template_directory_uri(). Both files will be defined after we create our whole WordPress gallery factory class.
Our method collect_galleries is used to collect all galleries that are added in the filter sortable_wordpress_galleries. We are almost done. Now we need to render those galleries in the admin area and also in the content.
In the method create_galleries we are hooking the method load_galleries to the actions inside the edit screens. These method will be used to instantiate every gallery that was collected. By instantiating our galleries, our metaboxes will be created.
The last part is the part where we render our galleries. We are first making sure that our galleries are loaded. Once that is done, we are going through all the loaded galleries and call their method render and passing the $content to them. Each gallery can have a different class and have a different rendering method so by doing it in this way, we are sure that our galleries will be rendered as intended.
The style is really minimum since we are using classes that the WordPress Media Uploader modal is using. We just have to define some simple CSS rules to display our images in the metabox correctly. This is our style:
This is the last part of this tutorial. If you have made it this far, I congratulate you already! This is the last piece of code that will connect everything. After this you can view a few of the examples on how to add different galleries. Let’s finish this!
I will separate our script file into several parts so that you could easily understand every bit of the code. First, we will create the function that will be used to open the WordPress Media Uploader and also add images to our input and WordPress gallery metabox.
We are passing two parameters to our function:
Here we define a variable file_frame that will hold our WordPress Media Uploader pop-up. Since we do not want the pop-up to get initialized every time we click on the button, we are checking if the variable file_frame is already set. If it is set, then we will open the previously opened WordPress Media Uploader.
If file_frame is not set, then we need to define the WordPress Media Uploader pop-up. We initialize it and allow multiple selection. After that we define a function that will get called once the frame is open. Once it is open, we get the selection object and the image IDs from our hidden input. We are immediately creating an array of the image IDs from the hidden input by splitting the value with each comma (,).
For each image ID we create a WordPress Media attachment and fetch the data for that attachment. The last thing we do is add the attachment to the selection. Now every time the WordPress Media Uploader is open, all our images will be selected so that we do not have to select them all again.
Now that we defined what our file_frame will do when it is opened, we need to define also the function that will get triggered when we select all the images and click the insert button. When we click the insert button this will happen:
Once everything has been set we just need to open our WordPress Media pop-up. We have two functions which are used in the above code that have to be defined. We will now define the function sortable_gallery_image_create that is used to create the image out of the attachment object.
In this function we create the output for one image. The HTML here is the same as we did the one in our class Sortable_WordPress_Gallery and method render_meta_box_content. The only difference here is that we populate it from the parameters we pass into this function.
The removal function is attaching the function to every element with the class .remove-sortable-wordpress-gallery-image. When we click on that element we are getting the attributes values:
We also get the hidden input of our gallery by constructing the ID from the gallery ID and _input suffix. After that we remove our LI that was holding the image and the clicked element, we split the IDs from the hidden input to array and we get the index of the attachment ID in the array. If the index is 0 or higher then we remove it from the array. Once it is removed, we join all the other IDs to a string and set the value back to the hidden input.
Now all our functionality is done. The only part to do is to create a call on the button for adding images.
We are making sure that the document is ready and that all has been already rendered. We get the image buttons by the class .add-sortable-wordpress-gallery and we also call the function to attach the removal functionality of each of the images that are already there. For each of those buttons we get the gallery ID and the hidden input ID. We also get the image container and make the children of that container sortable. For our ordering to be possible, we need to update the sequence of our IDs in the hidden inputs’ value. This is done by calling a function once the sorting is done.
When the sorting is done, we get all the children elements inside that image container and for each of those elements we get their IDs and push them to an empty array. Once every elements’ ID has been pushed, we join the array elements by commas and set that new value to our hidden input.
Last thing is to create a click trigger on the button to open our WordPress Media pop-up by calling the previously defined function sortable_image_gallery_media.
Now we have our WordPress Gallery done and we can use them as we want.
Here are some of the examples on how to add WordPress Gallery metaboxes.
Only one Gallery
Show second Gallery only on Page
Have you ever created your own gallery? Do you have some galleries you like or plugins that you use for creating galleries? Share everything in the comments below!
Web Developer who mainly uses WordPress for projects. Working on various project through Codeable & Toptal. Author of several ebooks at https://leanpub.com/u/igorbenic.
In less than 2 weeks, I have earned $1,800 by working on a custom solution with Easy Digital Downloads without any prior experience. Let me teach you how you can too with various custom solutions.Get the eBook