Posts Tagged category

WordPress: single post template based on category #2

In my previous post I talked about a Lorelle blog post on creating single post templates for different categories.

After using the code snippets “has is” I tryed to build a more flexible solution so I’ve come up with this little function:

function getSingleTemplate(){
 
  $category = get_the_category();
  $templateName = TEMPLATEPATH . '/single_' . $category[0]->category_nicename .'.php';
 
  if (!file_exists($templateName)){
    $templateName = TEMPLATEPATH . '/single_default.php';
  }
  return $templateName;
}

This function must be called inside the single.php template: it gets the first post’s category, searches for a template named like “single_post_first_category_slug.php” and returns its path; if the file doesn’t exists it will return the single_default.php template path.

My single.php template:

<?php
$post = $wp_query->post;
include( getSingleTemplate() );
?>

WordPress: single post template based on category

Today, while trying to customize the single.php template for a specific category I found a pretty old article written by Lorelle:

Creating Multiple Single Posts for Different Categories.

Her tip is really simple and really useful: just rename your single.php to single1.php and create a new single2.php with your category specific layout; after that, create a new single.php file with this code:

<?php
$post = $wp_query->post;
if ( in_category('1') ) {
  include(TEMPLATEPATH . '/single2.php');
} else {
  include(TEMPLATEPATH . '/single1.php');
}
?>

So, if the post is in category 1 WordPress will use the single2.php otherwise it will use single1.php.

Updated

I wrote a more flexible solution: check it out.

Add a category filter to WordPress search form

WordPress has a simple function to build a search form for your blog and in this tutorial I’ll show you how to add a category filter to it.

< ?php get_search_form(); ?>

This function will look for a file called searchform.php inside your template folder: if it doesn’t exist it will output the standard search form. So, if it isn’t already in place, create your custom searchform.php and copy into it the default search form output. It should look similar to this:

<form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">
  <div>
    <label class="screen-reader-text" for="s">Search for:</label>
    <input type="text" value="" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="Search" />
  </div>
</form>

Read the rest of this entry »