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:
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.
Inserting a Shortcode into a Theme
But what if you wanted your shortcodes to work outside of your posts or pages? What if you wanted to have a shortcode work in your header, for example?
Putting a regular shortcode in your theme’s files will not work as it would if you put it in a post or a page. But there’s a way around that.
Simply insert your shortcode into the following line of code, and place it where you like.
<?php echo do_shortcode('[my-shortcode]'); ?>
Of course you will need to substitute [my-shortcode] for your actual shortcode. For example, I placed my category counting plugin shortcut above in my header like this:
<?php echo do_shortcode('[catcount]'); ?>
Actually, I made it part of a complete sentence like this:
The total number of categories is <?php echo do_shortcode('[catcount]'); ?>.
The result looks like this:
And that’s all there is to it. Voila! A shortcode inserted wherever you like.