Why WordPress shortcodes can be so useful
WordPress is one of the most used content management systems in the world. Countless plugins have helped the former blogger software to an enormous range of functions, with which the most diverse web projects can be realized. However, WordPress has remained true to one thing over the years: It is a system that can be operated by bloggers, editors and other copywriters even without HTML and CSS knowledge and is thus suitable as a fast and uncomplicated solution for the distribution of content on the World Wide Web.
So if you want to take your first steps as a web author, WordPress is the best choice. In addition, the WordPress developers have introduced in 2008 with the so-called shortcodes a feature that allows you to easily add dynamic elements to your editorial posts.
What is a shortcode?
The so-called shortcodes, which were introduced with the WordPress version 2.5, are short commands that can be placed within texts and are linked to a PHP code. This is either stored in the file functions.php or in a separate .php file, which is included in the file functions.php. If a page is called with a shortcode, WordPress makes sure that the corresponding script is executed and interpreted. So the visitor sees the content generated by the PHP function instead of the code. So, strictly speaking, the shortcode acts as a placeholder, for example for simple elements like a text excerpt or also for dynamic content types like popups or an image gallery.
Implementing a shortcode in WordPress is not a big challenge: They are inserted directly in the editor at the appropriate place in the post. So that WordPress recognizes the codes as such, they are placed in square brackets [ ]. For example, a shortcode has the form [current-posts]. In conjunction with the corresponding PHP function, this code displays other recently published posts at the selected position. The WordPress shortcodes can also be specified with additional parameters. For example, to limit the display of the most recently published posts to five, the shortcode just used can be extended as follows: [current-posts posts="5″].
Why WordPress shortcodes can be so useful
Above all, two aspects make shortcodes in WordPress so practical: On the one hand, even users who have no JavaScript or CSS knowledge can bring dynamism into their web project. Even the script language PHP, which is elementary for shortcodes, does not necessarily have to be mastered, since various shortcodes including the corresponding scripts are already available in WordPress by default. On the official homepage these are clearly listed. There you will also find instructions on how to use the respective Unlock shortcode and can use them. In addition, many WordPress users make their self-developed WordPress shortcodes available for free on various platforms such as SNIPPLR. Also, many plugins and templates offer their own shortcodes. So you only have to program yourself if you want to change an existing script or need a completely new script.
The second major advantage of Shortcodes is the time saverFor example, if you use a certain text passage, logo, or other element over and over again in your posts, placing an appropriately programmed shortcode is a huge time saver. If you want to change something about that element later, you don't have to do it for each article individually. You simply adjust the PHP code and the changes will be applied to all pages of your WordPress project that contain the shortcode.
How to create your own shortcodes in WordPress
It has already become clear that the core of a shortcode is the PHP script that is executed as soon as WordPress encounters a previously defined shortcode. However, the following is not so much about how to program such a script, because that would mean a basic course in PHP programming, which would lead away from the topic. Rather, in the following sections you will learn how to include shortcodes in WordPress, how to use them for your project and how to deactivate them again. The corresponding PHP code you add either in the file functions.php in the directory of the used theme or in a separate PHP file, which you embed accordingly. So that your own shortcodes do not disappear with the next update of the theme, you should create a child theme. This is done with a few steps, as the tutorial in the WordPress support forum shows.
Create callback function
The PHP function that is executed as soon as WordPress registers a shortcode is a so-called callback function. As such, it is passed to another function as a parameter and called under defined conditions with defined parameters. The following example function searches the database and creates a link to the last post for the shortcode [current-posts]:
function current_posts_function() {
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string = '<a href="/en/'.get_permalink().'/">'.get_the_title().'</a>';
endwhile;
endif;
wp_reset_query();
return $return_string;
}
The text that should replace the shortcode is in the variable $return_string (PHP marks all variables with $). The PHP function (current_posts_function) returns this variable by return. If you accidentally use the echo command instead, the element implemented by shortcode suddenly comes before the actual content.
Add shortcode to WordPress
You need to tell WordPress that the function you created is a shortcode that should be executed automatically when a called page contains the [current-posts] shortcode. To do this, add the following code to your PHP file:
add_shortcode('current-posts', 'current_posts_function');
With this you have defined on the one hand the name of the shortcode [current-posts] you will use later in the editor and on the other hand the function current_posts_function() to be used. To avoid conflicts between different WordPress shortcodes, it is important to choose a unique name.
Define shortcodes parameterized and functionalized
To make your WordPress shortcode even more flexible, you can add optional parameters. In the example used so far, it makes sense to specify in the shortcode exactly how many posts should be displayed. For this you need two more functions: One is the shortcode_atts() function, which combines user-generated shortcode attributes with native attributes and automatically inserts required default values. Second, the PHP extract() function is needed to extract the shortcode attributes. In case the argument field is left empty, the default value 1 ('posts' => 1) must be specified:
function current_posts_function($atts){
extract(shortcode_atts(array(
'posts' => 1,
), $atts));
$return_string = '<ul>';
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string .='<li><ahref="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
endif;
$return_string .= '</ul>';
wp_reset_query();
return $return_string;
}
Now, if you specify the shortcode in the text as follows [current-posts posts="5″], it will display not only the most recently published article, but a list of the five most recent articles.
Using specific content as a shortcode parameter
You can further modify the presented example and additionally add a very specific content element as a parameter. In our example, this content parameter is to define the title of a heading. To do this, extend the callback script with the variable $content and insert the HTML heading before the enumeration:
function current_posts_function($atts, $content = null) {
extract(shortcode_atts(array(
'posts' => 1,
), $atts));
$return_string = '<h3>'.$content.'</h3>';
$return_string .= '<ul>';
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string .= '<li><a href="/en/'.get_permalink().'/">'.get_the_title().'</a></li>';
endwhile;
endif;
$return_string .= '</ul>';
wp_reset_query();
return $return_string;
}
Now surround the desired heading in your text with an opening and a closing shortcode, similar to an HTML tag:
[current-posts posts ="5"]Heading of the listing of current articles[/current-posts].
Using the WordPress Short Code in a Widget
So far we have dealt exclusively with the use of shortcodes in the WordPress text editor. However, there are often situations where shortcodes are also interesting for a widget like a sidebar. By default WordPress does not recognize the shortcodes there, but with a small additional line of code in the PHP file this can be quickly changed:
add_filter('widget_text', 'do_shortcode');
With this code you instruct WordPress to also check text elements in widgets for shortcodes.
Deactivation of shortcodes that are no longer needed
If you no longer need a particular WordPress shortcode, you have two options to disable it: The optimal solution would be to remove the callback function from the PHP file and all entries of the code from your posts. If you delete only the callback function instead, WordPress will no longer recognize the shortcode as such and will output it in plain text in the middle of the article. Since this method is very time-consuming for a frequently used shortcode, there is a second option for such cases: Instead of deleting code and PHP function, the callback function is extended by a nothing returning statement and thus quasi blocked:
add_shortcode('current-posts', '__return_false');
Useful shortcodes for your blog
Now that you have a little insight into the structure of shortcodes and know how to register and embed them in WordPress, the following examples should give you an idea of the many possibilities of the shortcode technique.
Insert link button
To add a link button with custom label to your project, all you need is a shortcode with the following callback function:
function link_button_function( $atts, $content = null ) {
return '';
}
add_shortcode('link-button', 'link_button_function');
The desired button label is simply placed between the opening and closing shortcode:
[link-button]Click here![/link-button]
Display of the menu of WordPress
With the following code you can display a selected menu of your WordPress project below the text post:
function menu_function($atts, $content = null) {
extract(
shortcode_atts(
array( 'name' => null, ),
$atts
)
);
return wp_nav_menu(
array(
'menu' => $name,
'echo' => false
)
);
}
add_shortcode('menu', 'menu_function');
If you want to use this shortcode, just specify the name of the corresponding menu as a parameter, e.g:
[menu name="Main Menu"]
The easy way to WordPress shortcode are plugins
For all those who neither want to create their own shortcode nor implement the prefabricated copies manually into functions.php or the respective PHP file, there is another way to unlock the useful shortcodes for your own web project: On the official WordPress homepage you can find a large selection of plugins that add both single and several different shortcodes to your WordPress installation. For example, with the Last Updated Shortcode extension you can access the shortcode of the same name [lastupdated], which shows when an article or page was last updated.
With over 50 shortcodes and its own CSS editor, the plugin Shortcodes Ultimate is somewhat more extensive. With it, WordPress can be extended, for example, with shortcodes for tabs, buttons, boxes or sliders. However, when using shortcode plugins, you should always keep the following in mind: The extensions consume computing resources and slow down your web project if used excessively. In addition, you usually don't know whether a Plugin further developed and regularly updated or whether it represents a security vulnerability.
Finally, it is worth mentioning that there are not only plugins that implement shortcodes, but also those that help you create your own callback functions and manage your shortcodes.
Shortcoder: You can create your own shortcodes in a visual editor and easily add HTML and JavaScript snippets to them.