九种页面都能打开了,但都只有一栏内容。这一篇加侧边栏——注意顺序:先在 functions.php 里注册,再在模板里调用。反了就调不出来。
function itheme_widgets_init() {
register_sidebar( array(
'name' => '侧边栏',
'id' => 'sidebar-1',
'description' => '显示在文章页和列表页旁边',
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'itheme_widgets_init' );
id 是自己起的,后面调用要用同一个。name 是后台显示的名字。剩下四个参数决定小工具外面包什么标签,下一篇细讲。
<aside class="sidebar">
<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>
<?php dynamic_sidebar( 'sidebar-1' ); ?>
<?php endif; ?>
</aside>
is_active_sidebar() 先问一句「这个侧边栏里有没有东西」。没放小工具就不输出空壳子,免得页面上多出一块空白。
<?php get_header(); ?>
<main>
<?php /* 主循环…… */ ?>
<?php get_sidebar(); ?>
</main>
<?php get_footer(); ?>
get_sidebar() 跟 get_header() 是一个套路——搬文件。它去找 sidebar.php,没有就什么也不干。
要让文章页也有侧边栏,就在 single.php 里也加一句。
下一篇:为什么小工具默认长得像列表。
本系列:迭代式建主题 · 目录(72 篇) | 上一篇 (21) | 下一篇 (23)