Try Tuts+ Premium, Get Cash Back!
Quick Tip: Using Shortcodes in Theme Development

Quick Tip: Using Shortcodes in Theme Development

Tutorial Details
  • Version: Wordpress 2.5+
  • Difficulty: Beginner
  • Estimated Completion Time: 5-10 Minutes

The WordPress Shortcode API was introduced to WordPress in Version 2.5. Since then, it has become a widely used method for allowing quick customisation of layout and inserting certain formatting snippets. But shortcodes can be equally useful when creating WordPress themes – here’s how you can make full use of them!


Introduction

Shortcodes have many benefits if used properly in theme files. If you are familiar with preprocessor macros in C / C ++, then shortcodes can serve a somewhat similar function in WordPress. The basic purpose of using a shortcode is to replace the placeholder with your own custom piece of HTML code when the server sends the page to the client side. The steps involved in creation and implementation of shortcodes are as follows.

  1. Create a custom function for the shortcode. This function returns the HTML which will be replace the shortcode in the theme file.
  2. Add the shortcode to the system such that WordPress can recognize your shortcodes inserted in the theme files.
  3. Use the shortcodes in the theme file as needed.

In this Quick Tip, we are going to make use of shortcodes to display custom posts. I have given a detailed explanation about how to create custom post types and use blank themes at Nettuts+, but for this example, we will be modifying the default TwentyTen theme provided by WordPress.


Step 1.Writing the Shortcode Function

The function you create for your shortcode actually defines the purpose of the shortcode. A basic function can be defined in the following manner (you can add all the code at the bottom of your functions.php file):

// Defining the function used for displaying the Custom Project Post.
function project_shortcode( $atts ) {
	// Extracting the arguments for the shortcode.
	extract( shortcode_atts( array(
		'limit' => '10',
		'orderby' => 'date',
	), $atts ) );
	/* This is were we will write the code for fetching data
	 * and build the HTML structure to be returned in the $output variable
	 */
	$output = 'This will contain the final HTML output for your custom project loop.';	
	return $output;
}

Just be sure not to leave any whitespace at the end of the functions.php file as it can cause a problem. Now let's add some code to fetch the custom post 'project' and build the HTML structure which will replace our shortcode.

function project_shortcode( $atts ) {
	extract( shortcode_atts( array(
		'limit' => '10',
		'orderby' => 'date',
	), $atts ) );
	// Creating custom query to fetch the project type custom post.
	$loop = new WP_Query(array('post_type' => 'project', 'posts_per_page' => $limit, 'orderby' => $orderby));
	// Looping through the posts and building the HTML structure.
	if($loop){
		while ($loop->have_posts()){
			 $loop->the_post();
			 $output .= '<div class="type-post hentry"><h2 class="entry-title"><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
			 $output .= '<div class="entry-content">'.get_the_excerpt().'</div></div>';
		}
	}
	else
		$output = 'Sorry, No projects yet. Come back Soon.';		
	// Now we are returning the HTML code back to the place from where the shortcode was called.		
	return $output;
}

The '$atts' are the attributes provided along with the shortcode. PHP’s extract method is used to divide the array elements into variables so that they can be used directly within the function.

In this example, we are using the attributes passed in the function to create a custom query for fetching the “project” custom post data. Then we are looping through all the project posts returned.

Within the loop, we are fetching and appending the data to the output variable with the appropriate HTML tags. Once the loop is complete, the output variable contains the complete HTML code for our project list. This HTML code is returned and the shortcode used in the theme is replaced by this when the page loads.


Step 2. Adding the Shortcode to the Database

Now that we have created the function, we have to register it to the database along with the shortcode that will be used for it. We can do this with the
register_shortcode method provided by WordPress.

add_shortcode('projects','project_shortcode');

The first argument in this method is the name of the shortcode that we will use in the theme, and the second argument is the name of the function (which we defined above) relating to that shortcode. This is how WordPress will know what to do when that shortcode is parsed or encountered.


Step 3. Using the Registered Shortcode in the Theme

WordPress provides a shortcode parsing method which very few developers consider using all that often. The do_shortcode method can be used to insert shortcodes within theme files themselves.

The shortcode syntax is similar to what you would insert in the backend editor. In this case, we are passing the attributes for the limit of number of posts to be displayed, and how to order them. As we are displaying “project” custom posts, we will create a new dedicated page template and use the shortcode in that. Create a template named 'page-project.php' and use the following:

<?php 
/*
Template Name: Project Page
*/
?>
<?php get_header(); ?>
		<div id="container">
			<div id="content" role="main">
				<?php echo do_shortcode('[projects limit=10 orderby=rand]'); ?>
			</div><!-- #content -->
		</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>

Now to view the template you just created, create a page called 'Project'. Obviously create some demo “Project” posts as well!

Voila! The short code is displaying the custom posts successfully.


Conclusion

As you can see, the above method of creating a shortcode for custom posts and using them in our theme helps us to keep the theme files manageable and clean. This also has an added benefit that anyone can insert the custom post loop from the WordPress backend editor as well.

The above example shows how we can use shortcodes during theme development in an efficient way. There are many innovative and productive ways to make use of shortcodes in WordPress themes – feel free to share your own ideas in the comments!

Tags: tips
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://borayalcin.me Bora Yalçın

    nice and brief tutorial…gonna try this on my next project. thanks

  • Max li

    Thanks!
    i was wondering on how to implement this
    very useful tut. Also, could you make a tut about creating
    other types of shortcodes for wordpress?

  • http://yeuhost.info YeuHost

    Easy to understand with this article. :) Thanks for your branding open, WP Tutplus :)

  • Jose

    Nice tip, this can be used to display in an especified Page a blog ? am in like those portfolio themes that have a “blog” Page.

  • http://www.code-pal.com Sumeet Chawla

    Yup, you can also insert shortcodes in pages.

  • http://inspirationfeed.com inspirationfeed

    Great tips!

  • http://www.wpyag.com Ravi

    thank you for another great and very useful tutorials.

  • http://varemenos.com/ Varemenos

    Not really my favourite of tuts+ tutorials, sorry :(

  • http://www.webguide4u.com Vivek Parmar

    Shortcodes helps you a lot and Genesis and WooThemes offers it in their theme frameworks

  • http://www.glossyicon.com/ rajveer

    Thanks for sharing this valuable info!! keep it up !

  • http://web-geeks.com Techy

    Great post! Hopefully, you can finish part 3 of creating a WP Theme, I have been waiting for it for the past couple of days… I’m really glad you added WP Tuts+

  • No-No

    Bad bad practices. Shortcode is a plugin area;it’s not for themes.
    http://justintadlock.com/archives/2011/05/02/dealing-with-shortcode-madness

    • http://unrelatedmedia.ca Neil Davidson

      Agreed.

      Have common shortcodes? You seriously expect the average user to remember all 70+ codes just to insert list item images or other common elements? Theme forest themes are really, really bad for short code chaos. Most of those themes have over 400 lines of code in the functions.php file dedicated to short codes.

      Custom TinyMCE Button

      Add it to the TinyMCE editor instead of using shortcodes. It eliminates a lot of crap in your functions.php file and makes for an easy to remember reference for your users. You can even use tinyMCE.activeEditor.windowManager.open() to create entire forms with options to insert (such as which of the 20 list images to insert)

      For an extra ten minutes of your coding time you remove countless headaches in the future for yourself and your theme users.

      • http://www.moveupmedia.com Andy

        Good point Neil, in real world usage my clients will never get to a point where they can use (let alone remember) shortcodes. They need the simplest route possible. Thanks for your addition to this otherwise excellent article.

      • http://twitter.com/juarezpaf Juarez P. A. Filho

        Really good point Neil… I think that’s the better way, clients really don’t like shortcodes. I need to read the article mentioned by No-No. o/

  • http://jatinhariani.pcriot.com/ Jatin Hariani

    nice tutorial.
    More detailed tutorials on shortcodes would be welcome!

  • David

    Where should I put the add_shortcode call? header.php or functions.php

  • al

    has anyone ever developed a shortcode to show archives in the format by month and list the posts under the month title?

    July 2011
    - 4 Post Title

    June 2011
    - 30 Post Title
    - 20 Post Title

    I really do want to see the post title and date in the archives list, sorted by month and post title

    Al

  • Kaiser

    Step 2: Adding shortcodes to your “Database”?? Since when are shortcodes added to the database? This is only one of the many things that make this tutorial “great”. Thanks.

    • http://www.code-pal.com Sumeet Chawla

      Adding shortcode to the ‘database’ is basically referring to the fact that you are registering your custom shortcode to wordpress. My bad I put it in a wrong way. Its basically adds a hook for the shortcode custom tag that you want to create…

  • Connor Crosby

    Awesome, clear tutorial. Thanks Sumeet :)

  • rathis

    good one…
    but need help in .htaccess file for redirectin my website from a folder to other one…
    eg: old one …/http/site1/
    new one to …./http/site2…

  • Pingback: Link Heaven | Mihai Baboi

  • http://just4dj.com Artem

    Nice, but it’s very hard tutorial for me…

  • Pingback: 40+ Best WordPress Tutorials of July 2011 - Wordpress Tutorials

  • http://refreshdays.blogspot.com Purushottam Kushwaha

    well do_shortcode() function woks well but suppose we have closing tag of shortcode and we have to insert some data in between. hen could u suggest any method.
    for example: if we have a shoortocde
    [li style="plus"]content goes here [/li]
    then in terms of page template how do we write this
    will it be

    It doesn’t work. I tried many combination to do that but couldn’t find a way out.
    Please help!!!

    • http://youtube.com/izvarzone AntoxaGray

      What’s reason to make shortcodes that do exact same thing as original tag?

  • Pingback: Best WordPress Tips and Tutorials | Designs Showcase

  • Pingback: How to Create an Instant Image Gallery Plugin for WordPress | Wptuts+

  • Pingback: How to Create an Instant Image Gallery Plugin for WordPress | How to Web

  • Pingback: How to Create an Instant Image Gallery Plugin for WordPress | 87studios.net

  • http://www.wordpressguru.com.au/ Wordpress Developer Sydney

    just going to some resources after seeing jeffery’s video about shortcodes … good tutorial

  • http://www.facebook.com/mittul.chauhan Mittul Chauhan

    we can also use this superb plugin if we dont know how to code ..

    http://wordpress.org/extend/plugins/shortcodes-ui/

    this is why wordpress has made for. . less code and do more .. great wordpress

  • Vijay Kudal

    I am using plugin like to read http://wordpress.org/extend/plugins/like-to-keep-reading/
    problem is its using opening and closing shortcodes,when I embed them to my site http://vijaykudal.info only opening short codes displayed,can you please help me?

    PS:-tried with different themes as well