Thoughts Of A North Wales Web Developer

Create Your Own WordPress Shortcodes

As we delve deeper and deeper into the possibilities of WordPress and we endeavor to create weird and wonderful themes for our blogs, clients or just for fun, one thing we are all striving for is allowing our users (including ourselves) a hassle free and intuitive system with which they can interact. As of version 2.5 we have been introduced to the magic of shortcodes. Shortcodes allow us to include, often complex, code with a simple key word. For example if you attach images to a post and want to show them in the post as a Gallery you can use the following simple code in the post editor
[gallery]
This will create all the necessary (X)HTML for your gallery.
Not only are shortcodes often overlooked, but few know that you can easily create your own without messing with the WordPress core.

Creating a Simple Short Code

The first thing you will need for this is a functions.php file in your theme directory. If you don’t have one you can create one, no extra code is needed just a blank file saved as function.php.
We are going to create a shortcode that returns the url of your blog.

function myUrl() { // Define function that will be used by the shortcode
      return get_bloginfo( 'URL' ); // WordPress function that returns the URL of the blog
}
add_shortcode('blogurl', 'myUrl'); // Add the shortcode to the theme, in this format add_shortcode('shortcode_name', 'function_to_execute' )

Save and upload your functions.php and you can now use the shortcode [blogurl] which will return the full url of your/the blog.
This can be widely expanded upon, such as returning adsense code, and I plan to share some of mine in a later post.