標籤:wordpress
近日,因為網站建設的需要,在沒有使用自訂文章類型的情況下,使用不同的分類目錄裡的文章調用不同的模板,作為註冊wordpress大學的見面禮。
首先在function.php裡,添加如下代碼:
//擷取並輸入某個分類的子分類
function post_is_in_descendant_category( $cats, $_post = null )
{
foreach ( (array) $cats as $cat ) {
// get_term_children() accepts integer ID only
$descendants = get_term_children( (int) $cat, ‘category‘);
if ( $descendants && in_category( $descendants, $_post ) )
return true;
}
return false;
}
複製一份single.php,命名為:single-*.php檔案名稱(你可以根據自己的需要,製作多個 single-*.php 檔案,通過修改每個single-*.php 檔案的html結構和添加對應的CSS,就可以實現不同的文章頁面樣式 )。
將 single.php 裡面除了 get_header(); get_footer(); get_sidebar(); 之外的所有內容改成:
<?php
if ( in_category(‘16‘) || post_is_in_descendant_category(16) )//可自行修改 這裡包含分類目錄裡的文章和分類目錄裡的子分類目錄裡的文章
{
include(TEMPLATEPATH .‘/single-16.php‘);
}
elseif ( in_category(‘7‘) || post_is_in_descendant_category(7) )//如果只有兩類single.php,可以不要這段,如果是多類,則添加多個elseif
{
include(TEMPLATEPATH . ‘/single-7.php‘);
}
else{
include(TEMPLATEPATH . ‘/single-other.php‘);
}//給其他分類的文章調用的。
?>
倡萌註:該文章的方法和倡萌之前分享的《WordPress不同分類使用不同的文章模板》的方法二一樣,就是使用 in_category() 函數來判斷,不同的地方就是添加了自訂函數 post_is_in_descendant_category() 來擷取某個分類的子分類。
如果有更多的技術技巧分享也請在www.diandian100.cn聯絡我,謝謝大家的分享