Salvatore
Salvatore

Reputation: 21

How to create different post layout for different categories and subcategories in wordpress

I've modified the single.php file in order to change layout for each category. In single.php I have this code

<?php
$post = $wp_query->post;
if ( in_category( '26') ||  get_term_children('26') {
include(TEMPLATEPATH . '/single-ric.php');
}
elseif ( in_category( '36') ||  get_term_children('36') {
include(TEMPLATEPATH . '/single-parl.php');
}
else {
include(TEMPLATEPATH . '/single-all.php');
}
?>

Is there something wrong in this code? Each post article is shown with single-ric.php layout

Upvotes: 0

Views: 1188

Answers (1)

vard
vard

Reputation: 4136

Your question address few issues. First, as Pieter stated, you should use get_template_part instead of TEMPLATEPATH as it is deprecated.

What you need to do is to rename your templates to something like singlepost-ric.php, singlepost-parl.php and singlepost.php (instead of singlepost-all.php - that will be your fallback), this to prevent any fallback loop conflict - you need to place them at the same level as single.php to make this work. Then, use get_template_part in this way:

get_template_part('singlepost', 'ric');

If this doesn't work, use this to get the possible error messages:

assert("locate_template( array('singlepost-ric.php', 'singlepost.php'), false, false )");

The other issue is, and why your first condition is always true, is that you don't use right get_term_children. This function is used to get all the childrens of a term in a single array. If it don't find any, it will return an empty array, not false. This is why this (in_category( '26') || get_term_children('26')) is always true. By the way, you're missing a closing parenthesis in all your conditions.

I assume that what you want to do, is to know if the current post is in the category 26. Just remove the get_term_children part - it address something else. You probably added this because a category is a taxonomy, which would be valid then, but in_category is enough.

Last thing, you don't need this:

$post = $wp_query->post;

It is redundant. As you're within a template, the global var $post already contains the post you query.

Upvotes: 1

Related Questions