The Guide to Creating Custom Shortcodes in WordPress

The simplest way to portray shortcodes is to define them as an easy way to add dynamic content into your WordPress posts, pages, and sidebars. Plenty of WordPress plugins and themes have shortcodes as a means of adding specialized content like contact forms, image galleries, sliders, and more. The easiest way to get started with creating and using shortcodes is with a shortcode plugin. However, if you are interested in creating custom shortcodes in WordPress, buckle up, as this guide is for you. Mind you, this will require some technical expertise in coding, by you probably already know that.

So, there are two ways in which you can find WordPress shortcodes to be of use to you:

  1. they can reduce the amount of code you need to write,
  2. they simplify the usage of WordPress plugins, themes, and other functions.
A computer monitor with a WordPress site on it
Learning the way of creating custom shortcodes in WordPress will give you greater control of your website.

The process of preparing WordPress for custom shortcodes

While it is by no means a necessity, it is generally a good idea to keep your custom shortcodes in their own file. Otherwise, you can choose to add them to your theme’s functions.php file. Start with creating a new file named ‘custom-shortcodes.php’, and save it inside the same folder as your theme’s functions.php file. Then, inside the newly created file, you would add the following block of code:
<?php
?>
Upon doing so, you want to open the functions.php file, and add the following line of code:
include(‘custom-shortcodes.php’);
Congratulations! You are now ready to start creating custom shortcodes in WordPress.

Creating basic shortcodes in WordPress

We will explain the process of creating a basic WordPress shortcode through an example of inserting a simple avatar image. The first step is creating the shortcode function. Inside the custom-shortcodes.php file, you will add the following:

function simpleavatar_function()  {
return ‘<img src=”https://simpleavatar.com/wp-content/uploads/avatar-simple.png”
alt=”doti-avatar” width=”96″ height=”96″ class=”left-align”  />’:
}

In the code example above, the simpleavatar_function returns a pre-determined image named avatar-simple.png. The next step would be to register the shortcode with WordPress using the built-in function add_shortcode. Still inside custom-shortcodes.php, make sure that you add the following line of code:

add_shortcode(‘simpleavatar’, ‘simpleavatar_function’);

After you’ve registered a shortcode using the add_shortcode function, you will pass in the shortcode tag ($tag) and the corresponding function ($func)/hook that will execute whenever that shortcut is used. In this particular case, the shortcut tag is simpleavatar and the hook is dotiavatar_function.
Make sure that you only use lowercase letters when naming tags, leaving the hyphens out. Underscores, however, are acceptable.
So, now that you have created the shortcode, and registered it, it would be great that you try it out. Whenever you want the simple avatar to appear inside the post content, simply use the shortcode instead: [simpleavatar]

Coding process on a computer monitor
Upon creating and registering the shortcode, you always want to try it out.

Creating custom shortcodes in WordPress with parameters (attributes)

In the previous example, you didn’ have much room to change things up. And, let’s presume that instead of pushing a single image, you would like to be able to set which image to use using a parameter. A great way to do this is by adding some attributes ($atts). So, as before, inside custom-shortcodes.php, add another function:

function simplerating_function( $att=array() )   {

//set up default parameters

extract(shortcode_atts(array(

‘rating’=> ‘5’

), $atts));

return “<img src=\”http://simpleavatar.com/wp-content/uploads/$raing-star.png\”

alt=\”simple-rating\” width=\”130\” height=\”190\” class=\”left-align\”  />”;

}

What you have written above accepts a single parameter: rating. If a rating value is not passed, it will use a default string value of 5. It does this by unwrapping the array of attributes using the built-in shortcode_atts function and then combining the default values with values that might have been passed into the function. Make sure that you don’t forget to register the code:
add_shortcode(‘simplerating’, ‘simplerating_function’);

With the shortcode function created, and the hook added, the shortcode is ready to find its place inside your post content:

[simplerating rating=3]

That would be the gist of creating self-closing WordPress shortcodes. Howbeit, there is yet another kind you can create.

A man learing how to create custom shortcodes in WordPress.
If you are interested in manipulating the enclosed content, there is yet another way to create custom shortcodes in WordPress.

An additional type of shortcodes you can create: enclosing shortcodes

Up to this point, we have been explaining the self-enclosing shortcodes. However, there is another type of shortcode we would like to introduce you to: enclosing shortcodes.

These allow you to use a BBCode-style format. Such a style would look like this:

[shortcode]content[/shortcode]

Enclosing shortcodes are useful in a case when you need to manipulate the enclosed content. To further illustrate, let’s say that you have a particular style of button you use for your website. You could use the HTML code to generate that button/style every time you need to use it. However, you can also set up a custom enclosing shortcode to do it for you.

By utilizing an enclosing shortcode, you will be able to keep the focus on the content instead of the code.

Creating the enclosing shortcodes

You would once again to the custom-shortcodes.php file, and add what follows:

function simplefollow_function( $atts, $content = null )  {

return ‘<a href=”https://twitter.com/simpleavatar/”  target=”blank” class=”doti-follow”>’ . $content . ‘</a>’;

}

In this block of code above, the $content = null is used to identify this function as an enclosing shortcode. Inside that function, you are wrapping your content within the HTML code. You can probably guess the following step – registering the shortcode:

add_shortcode(‘simplefollow’, ‘simplefollow_function’);

Voila! The shortcode is ready to be used.

A man using WordPress for his blog
You now have better control of customizing your WordPress.

What it comes down to

Once you understand how creating custom shortcodes in WordPress works, you will find the process itself to be simple and effortless. However, if this seems to be too great of an endeavor for you, remember that you can circumvent the process altogether, and opt for plugins, themes, and other features that allow you to style the website to your liking.

404 error404 pageabove the foldadvanced cssAIDA modelakismet pluginbacklinks auditbehavior patternbounce ratebrowser compatibilitybulk deletecaching pluginscall-to-actionchild themecode snippetcolor schemecomment sectioncompetitors' backlinkscontact formconversion ratecreate child themeCTA buttoncustom pagecustom themedead linksdefault configurationdigital marketingdomain authorityeasy manageedit main pageediting toolsemail marketingengaging contentFAQ pluginsfilter spamfix site errorfolder structurefree pluginsfriendly toneGoogle analyticsgoogle rankingsGravity Forms pluginguest postingHeadless WordPressHow toimage optimizationincrease readabilityindex errorsinfluencer marketingkeyword researchlibrary assistantlink managementlink trackingloading speedlocal businesseslong-tail keywordsmedia replacemedia restrictionmobile optimizationmoney onlinemulti currency pluginsmysql queryonline presenceonline validatorpage builderpage creationpopup pluginproducts and servicesquality imagesquality serviceReact JSreaction buttonsredirect chainsresponsive designschema markupsearch rankingsearch termsSEO for bloggersSEO optimizationSEO professionalsSEO tipsSEO toolsshort linkssocial mediasocial media plugins for WordPressssh commandsstatic pagetargeted audiencetechnical performancetest metrictext formattheme setting uptime utilizationtips and trickstraffic increaseunique visitorsuser accessuser engagementuser experiencevisual designvisual elementsvisual reportweb crawlersweb hostingwebsite architecturewebsite auditwebsite designwebsite elementswebsite maintenancewebsite optimizationWebsite problemswebsite securitywebsite structureWhat’s new in WordPresswhite spacewoocommercewordpressWordPress admin email verification noticeWordPress debug modeWordPress functionalityWordPress pluginWordPress pluginsWordPress recovery modeWordPress responsive designwordpress securitywordpress themewordpress theme editwordpress tipsWordPress tips and tricksWordPress web hostingwp security

Newsletter