首先,下面第一组代码是single.php模板里的。
简述:
如果是当前详细页是photography分类的文章,那么在single模板中嵌入template-part文件夹下的content-photography.php代码片段。
如果是news(分类ID是230)分类下的文章,那么在single模板中嵌入template-part文件夹下的content-news.php代码片段。
这里有个关键点是,我们还需要判断,分类下有没有后裔分类。如果有,且依然要继承父级详细页的样式,那么还需要加一个判断条件post_is_in_descendant_category($id)。
下面例子中的判断条件if(in_category(230) || post_is_in_descendant_category(230)){…}目的就是,分类ID 230及其后裔分类下的文章都使用content-news.php代码片段。
<?php
get_header();
?>
<div class="page-container">
<div class="single-content">
<?php
while ( have_posts() ) :
the_post();
if(in_category(230) || post_is_in_descendant_category(230)){
get_template_part( 'template-part/content', 'news' );
}
if(in_category('photography')){
get_template_part( 'template-part/content', 'photography' );
}
endwhile;
?>
</div>
</div>
<?php
get_footer();
这里,post_is_in_descendant_category($id)是自定义函数。
关键函数:
将下面的代码,加入到functions.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;
}
}
评论区
发表新的留言
您可以留言提出您的疑问或建议。
您的留言得到回复时,会通过您填写的邮箱提醒您。