WordPress shortcodes: how to make your project more dynamic

WordPress is one of the most widely used content managements systems worldwide. Countless plugins have helped add to the former blogging software’s range of functions, allowing users to create a wide variety of different web projects. However, despite the monumental changes that the blogging platform has gone through over the years, in one aspect it has remained true to its roots to this day: it still remains a highly-accessible system that’s suited to bloggers, editors, and other writers, and these users don’t necessarily need to be experts in HTML and CSS in order to successfully spread their content throughout the World Wide Web.

Those who are thinking about taking their first steps towards becoming blogger or journalist will be very well equipped with WordPress. What’s more, In 2008 WordPress released its so-called ‘shortcodes’ feature, which allowed users to add dynamic elements to their editorial postings.

What are shortcodes?

Introduced with version 2.5, shortcodes are types of commands that are placed within texts and can be connected to PHP code. These are either stored in the functions.php file or in a separate .php data file, which is then added to the functions.php file. Whenever a site is called up with a shortcode, WordPress is responsible for executing and interpreting the respective script. This causes the viewer to see the content that’s been generated by the PHP function instead of the code. Strictly speaking, shortcode acts as a placeholder for simple elements like excerpts of text or more dynamic content types, like popups or image galleries, for instance.

Implementing shortcodes for WordPress is quite simple: they’re directly added into the editor at the exact location where they’re to appear within the entry. In order for WordPress codes to be recognised as such, they need to be put into square brackets [ ]. One popular shortcode appears as follows: [current posts]. When paired with the matching PHP function, this code will reveal recently published posts on the location where it’s been placed. Additional parameters allow WordPress shortcodes to be made more specialised. In order to limit the number of published articles that are to be displayed to a total of five, the shortcode can be expanded to look as follows: [current post post = “5”].

Why WordPress shortcodes are so useful

There are two reasons why shortcodes in WordPress are so practical: for one thing, they allow users that don’t have experience with JavaScript or CSS to make their web projects more dynamic. Knowledge of PHP, the language that shortcodes are based off, also isn’t necessary to get started with these features, as these shortcodes, including their corresponding scripts, are already included in WordPress by default. These are all listed on the official website of the CMS and are available free of charge. Additionally, users are able to find instruction manuals there on how the respective shortcodes can be activated and used. What’s more, many WordPress users offer their own independently developed WordPress shortcodes on different programmes like SNIPPLR or WPdevSnippts. Furthermore, many plugins and templates offer their own shortcodes. This means you only need to programme them independently if you want to change the existing script or need your own, entirely new script.

A further advantage of shortcodes is that they can help you save time: if, for example, you want to repeatedly use a certain text passage, logo, or another element in your entries, then placing a corresponding shortcode will save you an enormous amount of time. If you wish to then retroactively change something regarding an element without the shortcode, then you’re forced to do so separately for every single article. Adjusting the PHP code means that the changes will then be adopted for all of the pages of your WordPress project that contain this shortcode, hence, saving you time.

How to create your own WordPress shortcodes

At this point, it’s perfectly clear that the heart of the shortcodes is the PHP script that is automatically put into execution as soon as WordPress encounters a previously defined shortcode. The following paragraphs seek to give you insight on how to add shortcodes into WordPress, how to use these for your project, and how they can be deactivated again. The respective PHP code can be added either in the functions.php, located in the directory of the used themes, or in a separate PHP file. In order to be sure that your own shortcodes don’t disappear with the next update, it’s important to create a child theme. This can be completed in just a few simple steps as seen in the guide in the WordPress support forum.

Creating a callback function

The PHP function that’s executed as soon as WordPress registers a shortcode is a so-called callback function. This is then transferred to another function as a parameter and called up under the defined conditions with defined parameters. The following example function searches through the database and generates a link to a previously created entry 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="'.get_permalink().'">'.get_the_title().'</a>';
    endwhile;
  endif;
  wp_reset_query();
  return $return_string;
}

The text that the shortcode is supposed to replace is located in the variable, $return_string (PHP lables all variable with $). The PHP function (current_post_function) returns these variables with the variable, return. If you instead incorrectly use the echo command, then the element that’s been implemented via shortcode ends up in front of the actual content.

Register shortcodes in WordPress

You have to notify WordPress that the created function is a shortcode function that is to be automatically executed if the accessed page contains the shortcode [current post]. To this end, add the following code to your PHP file:

add_shortcode('current posts', 'current_posts_function');

With this step, you’ve now defined both the name of the shortcodes, [current posts], which will later be used in the editor, as well as the function, current_posts_function(). In order to make sure that no conflicts arise among the WordPress shortcodes, it’s important to choose a name that’s both unique and clear.

Defining shortcodes with parameters

In order to give your WordPress shortcode additional flexibility, users have the possibility of adding optional parameters. As seen with the previous example, it’s possible to determine within the shortcode just how many entries should be displayed. To this end, two further functions are needed: there’s the function shortcode_atts(), which combines user-generated shortcode attributes with native attributes and automatically produces standard values. The PHP function, extract() is also needed in order to extract shortcode attributes. In case that the argument field remains free, formulate the standard value 1 (‘posts’ =>  1):

function current_post_fucntion($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;
}

Just as is the case with an HTML tag, frame the desired title in your text with an opening and closing shortcode:

[current posts posts ="5"]Title of the list of current articles[/current-posts]

Using WordPress shortcode in a widget

Until this point, this article has detailed how to implement shortcodes in the WordPress text editor. There are often situations, however, in which these shortcodes can also be interesting for widgets like sidebars. By default, WordPress isn’t able to recognise shortcodes in these locations. But with a small line of additional code in the PHP file, it’s easy to get rid of this inconvenient circumstance:

add_filter('widget_text', 'do_shortcode');

This code signals to WordPress that the text elements in the widgets need to be inspected for the presence of any short codes.

Eliminating the need to turn off shortcodes

If you no longer need a certain WordPress shortcode then you have two possibilities for deactivating them: the best solution is to remove the callback function from the PHP file and all of the code’s entries. If you were instead only to delete the callback function, then WordPress wouldn’t be able to recognise the shortcode as such, and would then present the code in the middle of an article. Given that this method requires a lot of effort for shortcodes that are frequently used, there’s a further possibility for such cases: instead of deleting the code and PHP functions, the callback function is expanded through an unreturned instruction and thus blocked:

add_shortcode('current-posts', '__return_false');

Practical shortcodes for your blog

After you’ve begun to understand more about the structure of shortcodes and are also aware of how they are registered and faded into WordPress, then the following examples should help you learn more about the various possibilities that shortcode technology can afford users.

Adding a link button

In order to add an custom-designed link button to your project, you don’t need to do anything more than implement a shortcode with the following callback function:

function link_button_function( $atts, $content = null ) {
  return '<button type="button">'.do_shortcode($content).'</button>';
}
add_shortcode('link-button', 'link_button_function');

The desired font for the button should now be placed between the opening and closing shortcode:

[link-button]Click here![/link-button]

Displaying the WordPress menu

The following code allows you to display a selected menu from your WordPress project below a text entry:

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 code, then just enter the name of the respective menu as the parameter, for example:

[menu name="Main"]

Integrating Google Maps

Shortcodes technology enable excerpts from maps from Google Maps to be incorporated into your project without having to first adjust the source code. The appropriate code for your PHP file looks as follows:

function googlemap_function($atts, $content = null) {
  extract(shortcode_atts(array(
    "width" => '640',
    "height" => '480',
    "src" => ''
  ), $atts));
  return '<iframe width="'.$width.'" height="'.$height.'" src="'.$src.'&key=YOUR_API_KEY"></iframe>';
}
add_shortcode("googlemap", "googlemap_function");

The shortcode, which belongs to the standard short commands, is connected to the parameters height, widght, and the Google maps source (src). Following this, your code should look as follows when viewed in the editor:

[googlemap width="640" height="480" src= https://www.google.com/maps/place/Brandenburger+Tor/@52.5158015,13.3776636,233m?hl=de]

WordPress shortcode plugins: the easy way

For those who haven’t created their own shortcodes and also don’t wish to implement prefab examples into the functions.php (or the respective PHP file), there’s a further possibility of activating shortcodes for your own web project: on the official WordPress homepage you can find a large selection of plugins that allow you to add many different shortcodes to your project. The extension, last updated shortcode, makes use of the shortcode of the same name, [lastupdates], which displays when an article or a page was last updated.

With over 50 shortcodes and an individual CSS editor, the plugin, Shortcodes Ultimate Shortcodes Ultimate, offers a somewhat more extensive option. This allows users to add shortcomands for tabs, buttons, boxes, or sliders to WordPress. If you use Shortcode plugins, then you should always keep the following point in mind: extensions use up computing resources and will slow down your web project with excessive use. Additionally, most of the time it’s unclear whether these plugins will continue to be developed or updated or whether or not they present a security threat.

Finally, it should also be mentioned that there are not only plugins that implement shortcodes; some also exist in order to help you generate your own callback functions and manage shortcodes. To this end, the following three WordPress extension are helpful.

  • Shortcoder: users are able to generate their own shortcode in a visual editor and easily label these with HTML and JavaScript snippets.
  • Shortcodes in Use: this administration tool gives you an overview of the articles and pages where you’ve used shortcodes and where the respective codes actually come from (plugins, standard, or user-defined).
  • Shortcode Reference: by installing this plugin, users are able to receive a detailed overview on all the available shortcodes of your WordPress installation during content creation.

Wait! We’ve got something for you!
Get your .co.uk domain now, the first year is free.

Enter the web address of your choice in the search bar to check its availability.
12 month for £0/year
then £10/year