第一,比如你建立了一个单独的page页面:page-abc.php,仅仅需要在这个页面显示特定的侧栏,比如sidebar-one.php,那么就在page-abc.php中找到下面的代码:
<?php get_sidebar(); ?>
替换成:
<?php get_sidebar('one'); ?>
这样就直接调用需要显示侧栏。
第二、如果需要不同的文章分类,如电脑网络,其分类页面(就是点击“电脑网络”进入的那个页面),即主题中archive.php呈现出来的页面,以及该分类下文章的单独页面,就是点击“电脑网络”下所属“文章”进入的页面,即主题总single.php所呈现的页面,显示特定的侧栏,比如sidebar-two.php,那么首先请找到这个分类的ID:在后台“文章Post”-“分类Categories”目录下,把鼠标放到该分类名称上,看浏览器状态栏,或直接点击该分类,看浏览器地址栏:
……edit&taxonomy=category&tag_ID=123&post_type=post
其中123就是其ID。
然后写入代码:
<?php
if ( in_category( array( '123' ) ) ) {
include 'sidebar-two.php';
}else {
include 'sidebar.php';
}
?>
如果你想让ID为456的分类页面及该分类下文章的单独页面也显示sidebar-two.php,那就简单的不得了,将上述代码稍作调整:
<?php
if ( in_category( array( '123', '456' ) ) ) {
include 'sidebar-two.php';
}else {
include 'sidebar.php';
}
?>
但是如果你想让ID为789的分类页面及该分类下文章的单独页面显示sidebar-three.php,则应为:
<?php
if ( in_category( array( '123', '456' ) ) ) {
include 'sidebar-two.php';
} elseif ( in_category('789') ) {
include 'sidebar-three.php';
} else {
include 'sidebar.php';
}
?>
注意:上面第4行支持1个ID,要想包含多个ID,则需要像第2行,应用array。另外,按官方的CODEX中所示,ID部分也可以换成slug。
还有一种情况,就是你希望ID为10的分类及其子分类,各分类页面及分类下文章的单独页面显示sidebar-four.php的侧栏,而且子分类比较多,按照上面的方法,仅填父级分类的ID或者slug是不行的,必须把父级分类及子分类全部填上才行,就比较麻烦啦,那有什么办法吗,当然有!首先在archive、single等页面中加入以下代码:
<?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;
}
}
?>
紧接着,需要把上面的上面的那部分代码稍作调整:
<?php
if ( in_category( 10 ) || post_is_in_descendant_category( '10' ) ) {
include 'sidebar-four.php';
} else {
include 'sidebar.php';
}
?>
感谢:http://imdoc.net/computer-and-internet/wordpress-program/2021.html











发表回复