Back

How to Easily Create WordPress Shortcodes

It’s a question I often get time and time again. “How do I create short codes in WordPress?”. Well – believe it or not, it is actually very simple – and requires maybe 10 minutes of your time to get a basic understanding.
WordPress shortcodes can easily be added in the functions.php file (Which can conveniently be edited via the WordPress theme editor UI. For this tutorial, we will be adding content to that functions.php file. The short codes we create in this guide will be simple portfolio links.
Shortcodes consist of two pieces. The first being a function that returns the final “value” of the shortcode. The second being a line adding the shortcode to WordPress. Both can go in the functions.php file.
The example below shows a PHP function that builds the content that will be returned by the shortcode – add this to your functions.php file. The function is doing 3 things that we need to pay attention to.

The function receives the attributes passed in from the shortcode.
The function takes the attributes we care about, and assigns them default values in case we do not pass in our own.
The function uses these values to return an output for the shortcode. In this case, our output is an image wrapped in a link.

function displayPortfolioItem($atts) {
extract( shortcode_atts( array(
'image' => 'something.jpg',
'link' => 'http://somedomain.com/',
'title' => 'some title',
), $atts ) );

return "<a href="{$link}" class="portfolio-item" title="{$title}"><img src="{$image}" alt="cover"></a>";
}
Next, we need to make sure WordPress knows that this function is intended to be used as a shortcode. To do this, we simply add this additional line to our functions.php file….
addshortcode('portfolioitem', 'displayPortfolioItem');
This function tells WordPress that shortcodes referencing portfolioitem should function using the rules we set out in the displayPortfolioItem function. We do this by using the addshortcode  function, which is part of WordPress’s Shortcode API.
Our functions.php file should be good to go. Save and close the file, and test your new shortcode! The syntax we should use with the shortcode is:
[portfiolio_item link="http://somewebsite.com/" image="/images/myimage.jpg" title="My Portfolio Shortcode"
That’s it! Congrats on making your first shortcode with no help from nasty plugins, or big addons! This functionality can be expanded on immensely, and used in many different ways to make a publisher’s life easier. If you have any questions, or comments – please leave them below.

Other Blog Posts