[英]use single page template for all posts inside subcategories in wordpress
我有幾篇帖子,這些帖子在子類別(第3級)的幾個子類別下,當然,在所有類別中都一個parnet類別。
我想為所有帖子制作一個特殊的single.php頁面,但是
<?php if(in_category($id)) { include 'special-single-page.php'; }
僅適用於該類別下的帖子,不適用於子類別的子類別中的帖子。
有沒有一種方法可以為父類別的幾個子類別下的帖子包括文件?
顯然,wordpress已經為此准備好了腳本。 它是這樣的:
<?php if ( in_category( $id ) || post_is_in_descendant_category( $id ) ) {
// your code goes here
}
?>
但是您需要在主題的function.php文件中添加一個函數。 這是要添加的功能:
<?php
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;
}
}
?>
看看get_category_parents()
我不知道您的代碼的完整結構,但是下面是一些代碼可以幫助您入門,但是您可能需要對其進行調整。 林不完全確定是否會工作。
$parents = explode('/', get_category_parents( $id ));
if(!isset($parents)) {
if(in_category($id)) {
include 'special-single-page.php';
}
} else {
if(in_category($parents[0])) {
include 'special-single-page.php';
}
}
或類似的規定。
閱讀一下,您可能會找到更好的方法。 http://codex.wordpress.org/Function_Reference/get_category_parents
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.