A while ago I came across the excellent plugin for WordPress, comically named Shortcake. Shortcake is a UI for WordPress shortcodes which makes using shortcodes in your content much easier. Recently I worked on a project that required the client to add before and after photos. The solution was shortcodes and thanks to Shortcake it was a whole lot easier. Here is how I went about it.
If you want to learn more about how Shortcake works and what it does I would check our the plugin on WordPress.org as well as heading over to the Github repo. Essentially it means that when dealing with adding shortcodes a user never needs to actually type out code in the editor, they are presented with a more intuitive UI in the add media popup.
First of all I registered my shortcode in the normal way that I would do with any other shortcode, using the
add_shortcode hook built into WordPress core.
The above code adds a shortcode with two attributes. These are the before image and the after image and it expects and attachment ID for each. Therefore without using the Shortcode UI plugin we could now add a shortcode to our content like so:
[before_after_image before_image="100" after_image="101"]
On the front end of the site this would output the two images one above the other. I then needed some styles and some jQuery in order to make the before image show first, and the after image only show when a toggle button was clicked. The following jQuery handled the toggling of before and after images:
Perfect, this now outputs the following on the front end (there are some styles needed here of course!).
The problem of course without using the Shortcode UI plugin is that the user has to know the attachment ID and also type the shortcode into the editor. Well that is what the Shortcode UI plugin handles for you.
In order to get this working make sure you have the Shortcode UI plugin active and then you need to register your shortcode with the Shortcode UI plugin. In the case of this shortcode it was done with the following code:
Just those few lines of code allow us to create a better UI for adding the shortcode. In order to add a before after image, we can now click on the Add Media button, and choose Insert Post Element from the list on the left. On the screen are now all the shortcodes that registered shown with their chosen Dashicon. Clicking that displays a simple UI showing the fields you registered for adding the shortcode.
As you can see the above interface is much much better than typing out a shortcode in the editor! Not only that, but once you click insert element, the user never even sees the shortcode (as long as they stay in the visual editor) as the plugin handles the TinyMCE view too! You will need some styling in your editor-style.css file.