Inserting WordPress shortcode in a template/theme


Shortcode API is introduced in WordPress 2.5, it is a simple set of functions for creating macro codes for use in post content. For instance, the following shortcode (in the post/page content) would add a photo gallery or a form or anything into the page:

[shortcode]

It enables plugin developers to create special kinds of content (e.g. forms, content generators) that users can attach to certain pages by adding the corresponding shortcode into the page text.

The Shortcode API makes it easy to create shortcodes that support attributes like this:

[shortcode id="123" size="medium"]

The API handles all the tricky parsing, eliminating the need for writing a custom regular expression for each shortcode. Helper functions are included for setting and fetching default attributes. The API supports both self-closing and enclosing shortcodes.

But what should we do when we have to call the shortcode direct into the files of our template/theme ?

<?php echo do_shortcode('[shortcode]'); ?>

and if we want to add attributes to the shortcode then, write

<?php echo do_shortcode('[shortcode option1="value1" option2="value2"]'); ?>

What are Shortcodes?


Shortcodes, which many plugins take advantage of, are an easy and quick way to insert special kinds of content into your posts or pages.

A shortcode typically looks something like this one from a plugin that is supposed to display the number of categories on a site:

[catcount]

You just pop your shortcode into your post, and then behind the scenes everything gets called into the post in the way it should.

So in the case above, I might write a post that says the following:

The total number of categories is [catcount].

If I have 21 categories, then when the post is published it will read:

The total number of categories is 21.

If I add a category, then that number will automatically get bumped up to 22. Continue reading