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)

 Replacing [SHORTCODE] with whichever WordPress shortcode you wish to use.  Simple huh?  This is probably the best option for those setting up their first blog

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.

i.e.

[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:

This example will output something like

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

and

[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

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.

Incidentally, if you need web hosting then these guys are worth checking out - I've used them for a few websites; they're reliable, unlimited bandwidth and pretty cheap too.