Get to grips with shortcodes in WordPress
WordPress has a fantastic feature called shortcodes. Paul Maloney shows you how they work and offers up a few examples of shortcodes you can use in your WordPress install
Demo: netmag.clientden.com/shortcodes
WordPress has a fantastic feature called "Shortcodes," if at any point you have used WordPress you will more likely than not have seen shortcodes along the way.
Shortcodes made their first appearance back in version 2.5 and are used for creating macros for use in post content.
A typical shortcode looks like this:
[foobar]
So why use shortcodes? Well, for a start they are a super short way to add all kinds of content in a shorthand way, it saves repeating blocks of code and running into issues and errors. They can be used for a huge variety of things such as forms, galleries, buttons and ad placement for example.
The best thing about shortcodes are they work in the visual editor which enables your clients to use them without having to learn any HTML!
WordPress has a number of standard “built in” shortcodes which can be used in your WordPress install, a full list is here.
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
Today I wanted to show a number of shortcode examples that will either offer something you can use "out of the box" or inspire you to create your own shortcodes to make your (or your clients') life that little bit easier.
Warning: Before making any changes to your files, please ensure you back up your files as the functions.php file in particular will cause issues if you break it!
A sample button
Buttons are a great example of something you can use a shortcode for, a typical button code might look like this:
<a class="mybutton" href="http://www.netmagazine.com">Net Magazine</a>
Using shortcodes we can change it to this:
[button link="http://www.netmagazine.com"]Net Magazine[/button]
The following snippet we would add to our functions.php file:
function myButton($atts, $content = null) {extract(shortcode_atts(array('link' => '#'), $atts));return '<a class="mybutton" href="'.$link.'">' . do_shortcode($content) . '</a>';}add_shortcode('button', 'myButton');
This basically creates a new function (myButton) and allows us to add the content using "link."
As we added a class in the shortcode we can now style in up in our stylesheet like we would do for any other class.
That is a very basic example of how they work, when broken down it's a simple yet effective process. So now we have the basics down let's move on and I will run through a few other handy shortcodes I use frequently myself.
Google Adsense shortcode
Many WordPress installs make use of Google Adsense so I felt a shortcode for this purpose would be helpful.
Google generates your Adsense code like this:
<script type="text/javascript"><!--google_ad_client = "pub-XXXXXXXXXX";google_ad_slot = "XXXXXXXXXX";google_ad_width = 468;google_ad_height = 60;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
If we add the following snippet to your functions.php file:
function googleads() {return '<script type="text/javascript"><!--google_ad_client = "pub-XXXXXXXXXX";google_ad_slot = "XXXXXXXXXX";google_ad_width = 468;google_ad_height = 60;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>';}add_shortcode('adsense', 'googleads');
We can now show an Adsense block by simply adding:
[adsense]
For multiple sizes we would create a new function and a new shortcode such as [adense2].
Google Docs shortcode
Google Docs is an incredibly useful tool for viewing files in a multitude of formats, and if you offer your readers any documents there is a chance they might not have the correct software installed to view them, so using Google Docs is a great way to ensure that any content you wish to be viewed can indeed be viewed.
This can be used for a number of file format as Google Docs supports the following: .DOC .DOCX .XLS .XLSX .PPT .PPTX .ODT .ODS .PDF .PAGES .AI .PSD .TIFF .DXF .SVG .EPS .PS .TTF .OTF .XPS .ZIP .RAR
Functions.php
function docs_shortcode($attr, $content) {return '<a href="http://docs.google.com/viewer?url=' . $attr['link'] . '">'.$content.'</a>';}add_shortcode('doc', 'docs_shortcode');
Usage
[doc link="file.pdf"]READ PDF[/doc]
Google Map shortcode
Another useful Google service is Google Maps. Of late maps are a frequent occurrence in our WordPress installs so here is an easy way to add a map to a post or page.
Functions.php
function googlemap($atts, $content = null) {extract(shortcode_atts(array("width" => '',"height" => '',"src" => ''), $atts));return '<iframe width="'.$width.'" height="'.$height.'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'.$src.'&output=embed"></iframe>';}add_shortcode("map", "googlemap");
Usage
[map width="300" height="300" src="https://maps.google.co.uk/maps?q=london&hl=en&sll=53.800651,-4.064941&sspn=12.165846,33.815918&hnear=London,+United+Kingdom&t=m&z=11"]
The above snippet allows us to control the size and width each time we use the shortcode, but if we wanted the same size map all of the time we could define the width and size in the array:
function googlemap($atts, $content = null) {extract(shortcode_atts(array("width" => '400',"height" => '400',"src" => ''), $atts));return '<iframe width="'.$width.'" height="'.$height.'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'.$src.'&output=embed"></iframe>';}add_shortcode("map", "googlemap");
As a result the shortcode would be shorter and we do not need to include the width and height:
[map src="https://maps.google.co.uk/maps?q=london&hl=en&sll=53.800651,-4.064941&sspn=12.165846,33.815918&hnear=London,+United+Kingdom&t=m&z=11"]
Embed video shortcode
Videos are becoming an increasingly popular addition to many WordPress blogs, so much so WordPress now auto embeds a number of video services.
Not all video services are supported so here is an example for YouTube which can be altered to handle other video services.
Functions.php
function youtube($atts) {extract(shortcode_atts(array("value" => '',"width" => '640',"height" => '480',"name"=> 'movie',"allowFullScreen" => 'true',"allowScriptAccess"=>'always',), $atts));return '<object style="height: '.$height.'px; width: '.$width.'px"><param name="'.$name.'" value="http://www.youtube.com/v/'.$value.'"><param name="allowFullScreen" value="'.$allowFullScreen.'"></param><param name="allowScriptAccess" value="'.$allowScriptAccess.'"></param><embed src="http://www.youtube.com/v/'.$value.'" type="application/x-shockwave-flash" allowfullscreen="'.$allowFullScreen.'" allowScriptAccess="'.$allowScriptAccess.'" width="'.$width.'" height="'.$height.'"></embed></object>';}add_shortcode("youtube", "youtube");
Usage
[youtube value="QH2-TGUlwu4"]
When using the shortcode we just have to grab the video value, so the part after the v= (www.youtube.com/watch?v=QH2-TGUlwu4).
Help! Shortcode won't work in my template files!!
Shortcode doesn't work in your template files in the typical shortcode format, fortunately WordPress has a way of handling this.
By using the "do_shortcode" function we can use our shortcodes in the template files like so:
<?php echo do_shortcode("[adsense]"); ?>
Shortcode won’t work in my widgets
Shortcodes do not automatically work in widgets but we can enable this, if we add the following to our functions.php file:
add_filter('widget_text','do_shortcode');
Conclusion
I have covered the basics of shortcodes and what they can do and offer you, the examples above are easy to implement and offer enough insight for you to customise and expand for your own needs. Good Luck!
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of eight full-time members of staff: Editor Georgia Coggan, Deputy Editor Rosie Hilder, Ecommerce Editor Beren Neale, Senior News Editor Daniel Piper, Editor, Digital Art and 3D Ian Dean, Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Beth Nicholls and Staff Writer Natalie Fear, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.