Page 1 of 1

Custom Shortcodes for WordPress

Custom Shortcodes for WordPress
   0

A short description how to add your own ShortCodes to your WordPress based website.

One of the reason why WordPress is so popular is the ability to customize. This can be done with the enormous amount of (often free) plugins, or by writing custom code utilizing the WordPress powerful backend.

One of those customizable things are the so called “Shortcodes” where a simple tag (like a macro) handles a complex task or repetitive work.

I’ll show you in this article what Shortcodes are and to how to create your own custom ones with a simple example.




WordPress Shortcode – Short-what?

Shortcodes are commonly used when editing content of a Post or Page.

A good comparison would be comparing it with a “macro”;
A few simple code automatically executes complex or repetitive work, just to make life easier.

 Note:

Shortcode will not be executed when editing a text – rather it will be executed by WordPress once it prepares a text to be displayed to a user.This means that when you change the functionality of a Shortcode, that these changes also reflect in “old” articles where you used these Shortcode before!

 

Suppose we have this simple Shortcode:


[link to="http://www.weethet.nl" name="WeetHet"]

When processed by WordPress the following HTML could be what is being send to your browser:


<a href="http://www.weethet.nl"><img src="link_arrow.gif">WeetHet</a>

Of course this is just a simple example.

Keep in mind though that the function behind a Shortcode can do pretty much anything you’d like. As an illustration: at tweaking4ll I use a Shortcode to display the details of a download in a hint-window (name, size, category, link, etc.).

For example this Shortcode:


1
[downloadfile id=172]

generates this:

Download - Name My TV Series Windows (32 bits) 

Filename:  Name-My-TV-Series-v1.8.4-Windows-x86.zip
Platform:  Microsoft Windows
Version:  1.8.4b
File size:  15.4 MB
Date:  2017-09-30
 Download Now  Send me a cup of Coffee    

Shortcodes can also wrap around a chunk of tekst.

At tweaking4ll you can see this with the information blocks. Shortcode in the text editor will then look something like this:


[my_infobox]A tip, a warning, or some other useful info[/my_infobox]

Infobox as an example

While updating WeetHet.nl, moving to the new domain tweaking4ll, and migrating to WordPress, I quickly ran into the limitations of the default text editor TinyMCE. Not because the editor is bad, on the contrary, rather because I was spoiled rotten by the great tools I used to use for editing an article.

I was looking for an easy way to make those info-boxes, it was always the same repetitive work to make a nice and consistent info-box. Pretty quick I ran into the so called Shortcodes of WordPress but really wanted to create my own Shortcodes.

As an example, this is the (simplified) code I wanted to use for my info-boxes:


1
2
3
4
<div class="a_style">
    <img src="info_icon.png">
    The Content
</div>

Using Shortcodes this could look like this:


[my_infobox]The Content[/my_infobox]

here you see the use of such an info-box:

 Note:

A little extra CSS will spice up the dull HTML example.For example;
A picture in the upper left corner, a nice background and a fitting border.The CSS for this can be placed in the style.css of your theme. You can find this file in your theme folder (wp-content/theme/theme-name).

By the way … you can put pretty much anything in the content – except … Shortcodes … (unless you call a special function – explained later).

PHP Code behind the Shortcode

The behavior of the Shortcode is determined by a function written in PHP. The function is to be defined and placed in the functions.php of the theme you’re using (see your theme folder: wp-content/theme/theme-name).


1
2
3
4
function make_infobox($att, $content = null) {
    return '<div class="a_style">'.
           '<img src="info_icon.png">'.$content.'</div>';
}

Yes this is a simple example, but if you’re not very familiar with PHP:

Define the function make_infobox which can take the parameters $att and $content which will be empty (null) when omitted.
Send the text back (return) ‘<div class=”a_style”>’, ‘<img src=”info_icon.png”>’, $content, ‘</div>’. The periods between the text parts glues them together.

 CAUTION

Every definition of a Shortcode has two parameters, where $att is an array is and $content a string (‘The Content’ in the example).Every function should return a text! Do not use statements that output text like for example echo!

 

The $content is available when a Shortcode wraps around content with a open and close tag, here: [my_infobox] (open) and [/my_info_box] (close).

You might recognize this construct from HTML or XML where ‘/’ indicates a “close”.

Suppose you have the Shortcode: [my_tage code=”123″]

Then the $att array will hold the values passed. You’d call them as such: $att[“code”].

We do not use this in our example, but it’s easy to use.

Tell WordPress about your ShortCode

Now that we have a function that can handle all we need, we must let WordPress know that it has to use it when processing text.

For this we use the WordPress function add_shortcode() which we place in the functions.php file of the theme you are using, I always prefer to place this call after the function definition:


1
add_shortcode("my_infobox", "make_infobox");

The first parameter (myinfobox) defines the Shortcode we want to enter when editing text (no square brackets in this call!), the second parameter (make_infobox) tells WordPress what function in functions.php to call when it runs into this Shortcode.

All together now …

In the functions.php file we will now find (position in the file doesn’t really matter – just as long as you maintain this order):


1
2
3
4
5
6
function make_infobox($att, $content = null) {
    return '<div class="a_style">'.
           '<img src="info_icon.png">'.$content.'</div>';
}

add_shortcode("my_infobox", "make_infobox");

After saving the functions.php changes, try the Shortcode either in a new or existing post and click “Preview Changes” to see your handy work in action.

 TIP:

When using images (as in this example), it’s recommended to add the path to the image as an absolute path. Say you placed the image in your theme folder, then do something like this (get_bloginfo(“template_url”)):


1
2
3
4
5
function make_infobox($content = null) {
    return '<div class="a_style"><img src="'.
            get_bloginfo("template_url").'/info_icon.png">'.
            $content.'</div>';
}

Shortcode in a Shortcode?

The text passed to your function through $content will not be processed anymore by WordPress which means that Shortcodes in the text remain unprocessed and will be displaed as plain text.

You can however tell WordPress to do it again (only if really needed!).

Replace $content in your function by do_shortcode($content) as such:


1
2
3
4
function make_infobox($att, $content = null) {
    return '<div class="a_style">'.
           '<img src="info_icon.png">'.do_shortcode($content).'</div>';
}

More information

More and definitly more advanced info can be found at the WordPress Codex pages.

Support Us ...


Your support is very much appreciated, and can be as easy as sharing a link to my website with others, or on social media.

Support can also be done by sponsoring me, and even that can be free (e.g. shop at Amazon).
Any funds received from your support will be used for web-hosting expenses, project hardware and software, coffee, etc.

Thank you very much for those that have shown support already!
It's truly amazing to see that folks like my articles and small applications.

Please note that clicking affiliate links, like the ones from Amazon, may result in a small commission for us - which we highly appreciate as well.

Comments


There are no comments yet.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.



Your Comment …

Do not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.