這里指的是默認文章類型的模板(single.php,category.php)
應用場景:
默認文章默認有2個大類(新聞資訊、游戲資料)
新聞資訊下的所有子分類調用“新聞資訊列表模板,新聞內容模板”
游戲資料下的所有子分類調用“游戲資料列表模板,游戲資料內容模板”
文章列表頁category.php
在category.php做判斷
如果該子分類屬於“新聞資訊根分類”,則調用新聞資訊列表模板
如果該子分類屬於“游戲資料根分類”,則調用游戲資料列表模板
這里的關鍵是“判斷子分類是否屬於根分類的函數”
Wordpress沒有默認的函數,需要如下代碼:
//函數cate_is_in_descendant_category( $cats )
//參數$cats一個分類ID,多個分類用ID數組
if ( ! function_exists( "post_is_is_descendant_category" ) ) { function cate_is_in_descendant_category( $cats ) { foreach ( (array) $cats as $cat ) { // get_term_children() accepts integer ID only $descendants = get_term_children( (int) $cat, "category" ); if ( $descendants && is_category( $descendants ) ) return true; } return false; } }
is_category( $category )
參數:$category
(混合) (可選) 分類 ID, 分類標題 Title, 分類短標記 Slug 或者 ID數組, Title數組, slugs數組.
默認: None
實現操作
首先,復制兩個category.php文件分別取名為“category1.php” 和“category2.php”。
然后,把原先的category.php文件里面的內容全部刪除,並用下面的代碼進行替換:
<?php if ( cate_is_in_descendant_category( 2 ) ) { include(TEMPLATEPATH . '/category1.php'); } else { include(TEMPLATEPATH . '/category2.php'); }
?>
意思是:檢查分類頁ID,如果該ID屬於分類ID9,則顯示category1.php,如果不是,則顯示category2.php。
文章列表頁category.php
在single.php做判斷
這里的關鍵是“判斷子分類下的文章是否屬於根分類的函數”
Wordpress沒有默認的函數,需要如下代碼:
if ( ! function_exists( "post_is_in_descendant_category" ) ) { 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; } }
in_category( $category , $_post )
參數1:$category
(混合的)(必選的)一個或多個被指定分類ID,分類別名或slug,或一個數組。
默認: 無
參數2:$_post
(混合的)(可選的)文章,默認為在主循環內的當前文章或在主查詢中的文章。
默認: 無
實現操作
首先,復制兩個single.php文件分別取名為“single1.php” 和“single2.php”。
然后,把原先的single.php文件里面的內容全部刪除,並用下面的代碼進行替換:
<?php
if ( cate_is_in_descendant_category( 2 ) ) { include(TEMPLATEPATH . '/single1.php'); } else { include(TEMPLATEPATH . '/single2.php'); }
?>
意思是:檢查日志,如果日志屬於分類ID9,則顯示single1.php,如果不是,則顯示single2.php。