2015-11-03 102 views
0

我修改了single.php文件以更改每個類別的佈局。在single.php我有這個代碼如何在wordpress中爲不同的類別和子類別創建不同的帖子佈局

<?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'); 
} 
?> 

這段代碼有什麼問題嗎? 每個帖子文章顯示與單ric.php佈局

+1

使用'get_template_part('single','all');'代替include(TEMPLATEPATH。'/single-all.php');'。如果我使用'get_template_part'('single','all');'不要使用'TEMPLATEPATH',這是折舊(*如果還沒有折舊*) –

+0

該頁面僅顯示標題而不顯示內容。我有同一個文件夾中的所有single.php,single-parl.php,single-all.php和single-ric.php。 – Salvatore

+0

如果get_template_part'找不到模板,那麼'get_template_part'會自動失敗,所以你可能有其他錯誤。激活調試模式(將_wp-config.php_中的'WP_DEBUG'常量更改爲true)並查看是否顯示任何錯誤。 – vard

回答

0

您的問題地址幾個問題。首先,如Pieter所述,您應該使用get_template_part而不是TEMPLATEPATH作爲it is deprecated

你需要做的是你的模板重命名爲類似singlepost-ric.phpsinglepost-parl.phpsinglepost.php(而不是singlepost-all.php - 這將是你的回退),這對防止任何備用環路衝突 - 你需要將它們在同一級別爲single.php,以使這項工作。

get_template_part('singlepost', 'ric'); 

如果這不工作,用這個來獲取可能的錯誤消息:

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

另一個問題是,爲什麼你的第一個條件總是然後,以這種方式使用get_template_part是的,你是不是正確使用get_term_children。此函數用於獲取單個數組中的所有術語的兒童。如果找不到,它將返回一個空數組,而不是false。這就是爲什麼這個(in_category('26') || get_term_children('26'))總是如此。順便說一句,你在所有條件下都缺少右括號。

我假設你想要做的是要知道當前的帖子是否在類別26。只需刪除get_term_children部分 - 它解決了其他問題。你可能加了這個,因爲一個分類是一個分類,這個分類是有效的,但是in_category就足夠了。

最後一件事,你不需要這樣的:

$post = $wp_query->post; 

這是多餘的。由於您在模板中,全局變量$post已包含您查詢的帖子。

+0

我跟着你的回答,但我仍然有空白頁,我可以在哪裏放'斷言(「locate_template(array('singlepost-ric.php','singlepost.php'),false ,假)「);' ?另一件事是我需要屬於cat 26和子類別的所有帖子都具有相同的佈局 – Salvatore

+0

只需在模板中使用'assert' - 如果'locate_template'可以找到模板,它將返回'true';否則返回'true' 。對於類別,'in_category(26)'對於屬於這個類別的帖子就足夠了。有關子類別,請參閱[本答案](http://wordpress.stackexchange.com/a/7615/62744)。 – vard

相關問題