WordPress 模板包含了 index.php(主页模板)、archive.php(Archive/Category模板)、404.php(Not Found 错误页模板)、page.php(内容页(Page)模板)、single.php(内容页(Post)模板)等主要文件。在这些文件中又引用了sidebar.php(侧栏模板)、header.php(Header模板)、footer.php(Footer模板)。
很多博友为了在不同页面的侧边栏中显示不同的功能,在 sidebar.php 文件中利用 is_single() 等方法来判断当前页面的类型来改变显示的功能。这样做虽然没有问题,但过多的 php 操作会影响网页响影速度。查看 index.php 等文件,会发现引用 sidebar.php 文件的功能是用 Wordpress 内置的 get_sidebar() 方法来完成的。该方法会在主题目录中查找 sidebar.php 文件,并将其包含进来。如果主题目录中没有 sidebar.php 文件,Wordpress 会将默认皮肤的 sidebar.php 文件包含进来(wp-content/themes/default/sidebar.php)。get_sidebar() 方法位于 wp-includes/general-template.php 文件中,内容如下:
function get_sidebar( $name = null ) {
do_action( 'get_sidebar' );
$templates = array();
if ( isset($name) )
$templates[] = "sidebar-{$name}.php"; // 根据 name 参数生成要包含的文件名
$templates[] = "sidebar.php";
if ('' == locate_template($templates, true))
load_template( get_theme_root() . '/default/sidebar.php');
}
get_sidebar() 方法有一个 name 的参数,该参数是可选的(大部分模板文件中没有指定这个参数),用来指定包含的文件名。例如希望 single.php 页面中包含自定义侧边栏文件 sidebar-single.php (必需保证该文件在模板目录下存在),可以加参数“single”:
get_sidebar('single');
同一个页面文件中也可以多次调用这个方法,比如一个页面包含了左右两个侧边栏:
get_sidebar('left');
get_sidebar('right');
了解这个方法的用法,我们清理掉 sidebar.php 文件中过多的判断语句,为不同页面打造更加丰富多彩的侧边栏。
| 五冠 Nokia/诺基亚 5230 5230XM 送证书V20版 内有港行 销数千台 | ||
| 1000.0元 | ||
| 批发 雷朋3025镜面反光太阳镜 太阳眼镜 19.9/副 顶级质量 | ||
| 19.9元 | ||
| 促销笔记本电脑 13.3英寸超薄N450无线网卡视频 | ||
| 1999.0元 | ![]() | |





