How to Make Your Own Wordpress [Shortcode]

Making your own custom Wordpress shortcode is actually very easy to do.  All you need to do is add a little bit of code to your site to generate a new Wordpress shortcode. Everyone loves the convenience of shortcodes such as the built in Wordpress gallery shortcode.  All you do is put [shortcodehere] into your post, and the gallery shows up

You may have used some plugins that implement their own custom shortcodes as well.  For example, if you want a poll in your post, your plugin may just tell you to throw something like this in your post:

[poll id=43]

That tells your blog to go get poll number 43 and place it into the post with all the proper formatting.

What if you wanted to make your own custom shortcode?

Easy enough.  For the sake of this example, lets say that you wanted to put a 300x250 square banner ad in the body of your post.  You don't always need this ad unit, so you would like to have the ability to just place it in the occasional post or page quickly and easily without having to remember all of the code.

When all is said and done, all you want to do is add [square_ad] to your post, and your custom shortcode will handle the rest.

Here's what you do.

STEP 1:

Locate your functions.php file in your themes folder.  If you do not have a functions.php file, just go ahead and make one.

STEP 2:

Paste this code into your functions.php file:

function post_ad() { 

return '<center>YOUR AD SERVER CODE GOES HERE</center>';

 }

add_shortcode('square_ad', 'post_ad');

Right there on line 3, you can see where I have labeled where to drop you ad code. So just take your Google Adsense code or other third party serving code ane place it in there.

Review the code parts.

function post_ad() {

In this first line of code, we are naming the function itself. This is not necessarily the name of the short code, but a way to reference the function. The post_ad part is the name. Call it whatever you want.

return 'YOUR AD SERVER CODE GOES HERE';

This is the important part. This is your third party ad code. However, it could be anything.

It could be a 3rd party script, a photo, or any other HTML that you want displayed.

If you do not want your item centered, no problem. Just remove the center tag parts.

Lastly, there is this bit of code.

add_shortcode('square_ad', 'post_ad');

The 'square_ad' part is where you actually get to come up with the shortcode to use. In this case, we would write [square_ad] anywhere on the page that we want this to show up.

The post_ad part is referencing back to the name of the function from a couple steps prior. This name should match the name of the function.

Finishing up.

Step 3:

That's pretty much it! Pop that code into your functions.php file and upload the file. On your next post, you should be able to just add your new shortcode to your post.

That's it! Give it a test drive to see how it goes. It should work out for you nicely.