Advertisement
Plugins

Quick Tip: Using Shortcodes in Theme Development

by

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!

Related Posts
  • Code
    Creative Coding
    Advanced Use of Attachments in WordPress: Creating Custom Queries for AttachmentsAdvanced use of attachments in wordpress 400
    This tutorial is the second in a four part series in which you'll learn some techniques for working with images in attachments in WordPress which give you advanced options.Read More…
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML: Creating an Archive TemplateCreating wordpress theme from html 400
    If you've been working your way through this series, you now have a functioning theme with two page templates. The steps I've demonstrated to this point are: preparing your markup for WordPress converting your HTML to PHP and splitting your file into template files editing the stylesheet and uploading your theme to WordPress adding a loop to your index file adding meta tags, the wp_head hook and the site title and description to your header file adding a navigation menu adding widget areas to the header and sidebar adding widget areas, a colophon and the wp_footer hook to the footer file creating template files for static pages. Read More…
  • Code
    Plugins
    Creating a Shortcode for Responsive VideoResponsive video shortcode main image 400
    If you're anything like me, you use YouTube to host any video you add to your WordPress site. It saves worrying about browser or device compatibility, it saves space on your servers, and it can be a lot more reliable.Read More…
  • Code
    Plugins
    Create a Shortcode to List Posts With Multiple ParametersPost listing shortcode main image400
    On many of the client sites I build, I find there are times when I need to include a post listing on a page. I'm not talking about archive pages here, but adding a custom listing to an existing static page. For example, I might want to list some posts on the 'About' page, or the site may require an in-depth page for a topic, with a list of posts and custom post types related to that topic. One way to do this is by creating a custom page template to include the current page content plus the results of a second custom query, but if you want more flexibility over how you list posts, or just want to do it a few times, a shortcode will be a simpler solution. In this tutorial, I'll show you how to create a simple shortcode to list all posts of a custom post type, and then I'll expand on that to create a shortcode with various parameters that users can specify to list posts however they want.Read More…
  • Code
    Plugins
    Integrating Multiple Choice Quizzes in WordPress – Creating the FrontendIntegrating multiple choice quizzes in wordpress
    This is the second part of the series on developing a multiple choice quiz plugin for WordPress. In the first part we created the backend of our plugin to capture the necessary data to store in the database. In this final part, we will be creating the frontend of the plugin where the users can take quizzes and evaluate their knowledge.Read More…