How to add Shortcodes to a WordPress theme

Want to add a shortcode directly to a WordPress theme without having to manually add it to each post or page?

Below are a variety of methods, from basic to advanced depending on your needs:

Basic Method of hard coding a Shortcode

Add the following code to either single.php (for WordPress posts) or page.php (for WordPress pages)

<?php echo do_shortcode("[SHORTCODE]"); ?>

Replacing [SHORTCODE] with whichever WordPress shortcode you wish to use.  Simple huh?

More advanced method – different Shortcodes in each WordPress Post

Supposing you need to use a different shortcode on each post, such as for a Gallery or Product Table.


[SHORTCODE id=’3′] for one page

[SHORTCODE id=’4′] for the next and so on

If this custom shortcode is based upon the ID of the post, then you can use something along the lines of this:

<?php echo do_shortcode('[SHORTCODE  id='. get_the_ID() .']'); ?>

This example will output something like

[SHORTCODE id=’3′] – for the WordPress post with the id of 3


[SHORTCODE id=’4′] – for the WordPress post with the id of 4 etc

Essentially it will result in [SHORTCODE¬† id=’YOUR POST ID WILL AUTOMATICALLY BE PUT HERE’]

More advanced still – adding custom Shortcodes to each WordPress Post Template!

Supposing you need to customise this further, and need to be able to edit the Shortcode variable for each individual post?

First you need to create a custom field for the Post – in the example below I’ve called it custom_field

Incidentally, there’s a good plugin for managing custom fields – check out Magic Fields 2 (it’s free and in the WordPress plugin directory)

Now that you’ve created this custom field, add the following to either single.php or page.php

<?php $var = get_post_meta($post->ID, 'custom_field', true);
if ($var == '')
{ }
else { echo do_shortcode( '[SHORTCODE  id="' . $var . '"/]'); } ?>

Now when editing the WordPress post, if you give the custom_field a value of 666 , then this will output

[SHORTCODE id=’666′]

or if you give the custom_field a value of Hello World, then this will output

[SHORTCODE id=’Hello World’]

Essentially whatever you type in the custom field will be outputted within the shortcode on every post or page using that template.

This should save you some time from having to add each shortcode manually, as well as giving you more freedom with the post or page layout.