wordpress不同页面显示不同的sidebar

这篇文章专讲 WordPress 如何让不同页面、不同分类页和文章页显示不同 sidebar。核心做法包括替换…


生猛大蝦 - opened book desk isle bookshelves school study class room background

第一,比如你建立了一个单独的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

❓ 延伸问答与排错指南(FAQ)
WordPress 单独页面怎么显示指定侧栏?

在对应的 page 模板里,把 get_sidebar() 改成 get_sidebar('one') 这类写法即可。前提是主题中存在对应的 sidebar-one.php 文件,这样该页面就会单独加载指定侧栏,而不影响其他页面。

分类页和文章页如何按分类显示不同侧栏?

可在 archive.php、single.php 等模板中用 in_category() 判断分类 ID,再用 include 加载对应的 sidebar 文件。多个分类可写成数组;若有多个分支条件,建议用 if/elseif 逐层区分,避免逻辑冲突。

父分类和子分类都要显示同一侧栏怎么办?

不要只写父分类 ID,因为子分类不会自动全部命中。文章里给出的方法是先定义一个判断后代分类的函数,再用“父分类 ID || 后代分类判断”来加载同一个 sidebar,这样父子分类都能统一显示。


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理。