get_sidebar(string $name = null)
是用来加载侧边栏模板的。
描述
为你的主题加载一个侧边栏,如果指定了参数名,那么将加载相对应的侧边栏。也就是说,如果你指定了参数名为”special“,就会加载”sidebar-special.php“文件。
参数#
$name
(字符串)(可选)默认是null
源码#
function get_sidebar( $name = null ) {
/**
* Fires before the sidebar template file is loaded.
*
* The hook allows a specific sidebar template file to be used in place of the
* default sidebar template file. If your file is called sidebar-new.php,
* you would specify the filename in the hook as get_sidebar( 'new' ).
*
* @since 2.2.0
* @since 2.8.0 $name parameter added.
*
* @param string $name Name of the specific sidebar file to use.
*/
do_action( 'get_sidebar', $name );
$templates = array();
$name = (string) $name;
if ( '' !== $name )
$templates[] = "sidebar-{$name}.php";
$templates[] = 'sidebar.php';
locate_template( $templates, true );
}
使用#
1、简单的调用
假设你在wp-content/yourTheme/sidebar-nice-bar.php,这个时候你就可以用下面的代码包含这个文件:
<?php get_sidebar('nice-bar'); ?>
2、简单的404页面
如果你的请求出现了404,你返回下的404界面(你也可以包含你主题中的404模板)。
3、左右侧边栏
两个侧边栏在一个主题中:
<?php get_header(); ?>
<?php get_sidebar( 'left' ); ?>
<?php get_sidebar( 'right' ); ?>
<?php get_footer(); ?>
左右侧边栏的文件名相对应sidebar-right.php和sidebar-left.php。
4、多个侧边栏
不同的侧边栏对应不同的页面。
<?php
if ( is_home() ) :
get_sidebar( 'home' );
elseif ( is_404() ) :
get_sidebar( '404' );
else :
get_sidebar();
endif;
?>
home和404的文件名对应着sidebar-home.php和sidebar-404.php。