How to Insert Shortcodes into a WordPress Theme


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.

Featured Plugin - WordPress Membership Site Plugin

If you're thinking about starting a paid, or just private, membership site then this is truly the plugin you've been looking for. Easy to use, massively configurable and ready to go out of the box!
Find out more

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.

 

Featured Plugin - WordPress Newsletter Plugin

Now there's no need to pay for a third party service to sign up, manage and send beautiful email newsletters to your subscriber base - this plugin has got the lot.
Find out more

 

Photo: Short pencil from BigStock

Tags

Comments (2)

  1. Hey i just wanted to say thanks (didn’t appreciate that i had to sign up to do that, ‘login with facebook’ usually doesn’t mean that) consider adding some social commenting options.

Participate