先在 functions.php 里注册:
add_action( 'widgets_init', function () {
register_sidebar( array(
'name' => '主侧栏',
'id' => 'main-sidebar',
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
} );
然后在 sidebar.php 里输出:
<aside class="sidebar">
<?php if ( is_active_sidebar( 'main-sidebar' ) ) : ?>
<?php dynamic_sidebar( 'main-sidebar' ); ?>
<?php else : ?>
<div class="widget">
<h2 class="widget-title">搜索</h2>
<?php get_search_form(); ?>
</div>
<?php endif; ?>
</aside>
else 分支里放一个默认搜索框——后台没配小工具时,侧栏不至于空白。
在首页、文章页、分类页里,把侧栏插进布局:
<div class="layout">
<div class="content">...主内容...</div>
<?php get_sidebar(); ?>
</div>
配一段 CSS:
.layout { display: flex; gap: 30px; }
.content { flex: 1; min-width: 0; }
.sidebar { width: 280px; flex-shrink: 0; }
@media (max-width: 768px) {
.layout { display: block; }
.sidebar { width: auto; margin-top: 30px; }
}
min-width: 0 是个小技巧:flex 子元素默认不会缩到内容宽度以下,长代码/长链接会把布局撑破。加这一句能解决。
<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url('/') ); ?>">
<label class="screen-reader-text" for="s">搜索</label>
<input type="search" name="s" id="s" value="<?php echo esc_attr( get_search_query() ); ?>" placeholder="输入关键词…">
<button type="submit">搜索</button>
</form>
三个要点:
name="s" 不能改(WordPress 认这个);method="get";value 里回填当前搜索词,用 esc_attr。label 配 screen-reader-text 这个 class,视觉上隐藏,但读屏软件能读到。这是无障碍的基本要求。
如果你用 placeholder 代替 label,读屏软件读不到(placeholder 不是标签)。所以两者都要有。
一句话记住:侧栏 = register_sidebar(functions)+ dynamic_sidebar(sidebar.php)+ is_active_sidebar 判空;搜索框 name 必须是 s。
下一篇做导航和移动端。