Thursday 14 November 2013

Using A Different Post Template For Posts Formats In WordPress

Important: All scripts hosted on widcraft.googlecode.com don't work anymore because Google has blocked that SVN repository.
Post Formats is a theme feature which was introduced with the WordPress 3.1 release. It gave us a new feature to style posts based on its format. If you ever used WordPress' default themes, then you might know about their different post templates based on the post format. So it's time for you to style your posts based on its format. Here's a demo of this trick from my own WordPress site:

This is a simple post.

This is a video post with a different template.

Add Post Format Support To Your WordPress Theme:

Before starting this tutorial, it's important for you to add support for post formats in your current WordPress theme. If this section is available in your post editor then you can skip this step:


If not, then follow this tutorial.

Using A Different Post Template:

In this tutorial, we'll create a different post template for the Video format. Most of developers uses a single post template file for all different format. But we'll use multiple single.php files to make it more easy and customizable.

Create a single.php file for your post format (we're using Video). We're going to name it single-video.php. You can also copy your single.php file to this template and make some changes that you want in the video template.

Upload single-video.php to the root of your current theme. Same place where single.php file is located.

Okay, so now we'll tell WordPress to use single-video.php template for the posts with video format. Add following to your theme's functions.php file:

add_action('template_include', 'load_single_template');
  function load_single_template($template) {
    $new_template = '';

    // single post template
    if( is_single() ) {
      global $post;

      // template for post with video format
      if ( has_post_format( 'video' )) {
        // use template file single-video.php for video format
        $new_template = locate_template(array('single-video.php' ));
      }

    }
    return ('' != $new_template) ? $new_template : $template;
  }

Save the file. That's it.

Now just publish a post with video format & see the magic. You can do the same with every post format. On a related note, I'll also share the same trick with categories, instead of formats.
Important: Check our new website TricksPanda.com for WordPress tutorials, plugins and more.
 
Powered by Blogger.