开发者

Multiple single.php in Wordpress based on category id

I am creating multiple layouts for the single.php in Wordpress based on the category a user selects. I have seen this with two categories and have done so in the past. But I have not tried it with more then two custom single.php files. It seems pretty straight forward. I have created some if statements in my single.php file that redirects the user to the proper template. However, I am just getting a blank page. Here is my code within the single.php file.

    <?php
$post = $wp_query->post;

if ( in_category('12') ) {
include(TEMPLATEPATH . '/single12.php');
}

elseif ( in_category('3') ) {
include(TEMPLATEPATH . '/single3.php');
}

elseif ( in_category('1') {
include(TEMPLATEPATH . '/single1.php');
}

else {
include(TEMPLATEPATH . '/singl开发者_开发知识库e-default.php');
}

?>


Have you declared global wp_query ? you might have error reporting off so that's why you're seing a blank page, so try :

global $wp_query;
$post = ...

Tough as a better practice you could use the following code ( not tested but it should explain what i mean for better practices ) :

global $wp_query;
$post = $wp_query->post;
$categoryes = get_the_category($post->ID);
if ( count($categoryes) > 0 )
{
    $disalowedCategories = array(4,6,8); // these categories should use single-default.php
    $category = $categoryes[0];
    $templateFile = TEMPLATEPATH . '/single' . $category->cat_ID . '.php';

    if ( file_exists($templateFile) && !in_array($category->cat_ID, $disalowedCategories) )
    {
        include($templateFile);
    } else {
        include(TEMPLATEPATH . '/single-default.php');
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜