0815

Du musst dich anmelden um Beiträge und Themen zu erstellen. Einloggen · Registrieren

Unique Single Post Templates for Different Categories

Here is an easy way to display custom post styles depending on the post’s category. With the following code, each single-view post will be displayed according to a template that is specific to the post’s category:

<?php $post = $wp_query->post;
if (in_category('1')) {
	include(TEMPLATEPATH.'/single-01.php');
} elseif (in_category('2')) {
	include(TEMPLATEPATH.'/single-02.php');
} else {
	include(TEMPLATEPATH.'/single-default.php');
} ?>

This code should be placed in your theme’s single.php file. As written, this code will display posts from the first category with the single template, “single-01.php”; also, posts from the second category will be displayed with a single template named “single-02.php”; finally, all other posts will be displayed via the default single template, “single-default.php”. Of course, you will want to customize the category IDs according to your own needs, and also you will want to create the customized single files as they are called. That’s all there is to it.

Having said that, here is an alternate version of the custom-post-template script:

<?php add_filter('single_template', create_function('$t', 'foreach((array) get_the_category() as $cat) { if (file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php")) return TEMPLATEPATH . "/single-{$cat->term_id}.php"; } return $t;')); ?>

Placed in your theme’s functions.php file, this alternate script checks all categories for the presence of a custom single template. Any category with a custom single-post template will then have its posts displayed with that template. If a post’s category does not feature a custom template, the default single.php template will be used. Note that this code will use the template for the first listed category of each post. Even so, you should only create custom post templates for categories that will always be mutually exclusive. That is, make sure that your posts aren’t in more than one custom-templated category.

Source: Austin Matzko




0