首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

WordPress 側邊欄完整指南:register_sidebar() 與 get_sidebar() 深度解析

     編輯:PHP 相關知識

一、register_sidebar() —— 註冊側邊欄區域

讓主題支援「小工具」的第一步,是在 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' );

二、get_sidebar() —— 載入側邊欄模板檔案

在前端模板(如 index.php、page.php)中呼叫,載入對應的側邊欄模板檔。

語法與檔案對應規則

get_sidebar( $name );
  • 無參數:載入 sidebar.php
  • 指定 $name:載入 sidebar-{$name}.php(如 get_sidebar('left') → sidebar-left.php)
  • 找不到檔案:回退載入 WordPress 核心 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.php
  • get_sidebar():wp-includes/general-template.php

總結

掌握 register_sidebar() 註冊區域與 get_sidebar() 載入模板的配合,即可建立靈活、可視化管理的側邊欄系統,是 WordPress 主題開發的基礎核心技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved