讓主題支援「小工具」的第一步,是在 functions.php 中掛載 widgets_init Hook 註冊側邊欄。
register_sidebar( $args );
$args = array(
'name' => __( 'Sidebar name', 'theme_text_domain' ),
'id' => 'unique-sidebar-id', // 必須小寫,唯一識別碼
'description' => '',
'class' => '',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
);
| 參數 | 說明 |
|---|---|
| name | 後台顯示的側邊欄名稱 |
| id | 唯一識別碼(小寫),供 dynamic_sidebar() 呼叫 |
| description | 後台小工具區塊的說明文字 |
| class | 給該側邊欄內所有小工具的額外 CSS class |
| before_widget | 每個小工具輸出前的 HTML 開頭標籤 |
| after_widget | 每個小工具輸出後的 HTML 結尾標籤 |
| before_title | 小工具標題前的 HTML |
| after_title | 小工具標題後的 HTML |
function my_theme_widgets_init() {
register_sidebar( array(
'name' => __( '右側側邊欄', 'my-theme' ),
'id' => 'sidebar-1',
'description' => __( '右側邊欄的小工具區域。', 'my-theme' ),
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
) );
}
add_action( 'widgets_init', 'my_theme_widgets_init' );
在前端模板(如 index.php、page.php)中呼叫,載入對應的側邊欄模板檔。
get_sidebar( $name );
sidebar.phpsidebar-{$name}.php(如 get_sidebar('left') → sidebar-left.php)wp-includes/theme-compat/sidebar.php<?php get_header(); ?> <?php get_sidebar( 'left' ); ?> <!-- 左側邊欄 --> <div id="content">...</div> <?php get_sidebar( 'right' ); ?> <!-- 右側邊欄 --> <?php get_footer(); ?>
register_sidebar():wp-includes/widgets.phpget_sidebar():wp-includes/general-template.php掌握 register_sidebar() 註冊區域與 get_sidebar() 載入模板的配合,即可建立靈活、可視化管理的側邊欄系統,是 WordPress 主題開發的基礎核心技能。