要在 WordPress 裡新增可以讓管理員在小工具那邊自己設置網站的區塊,可以參考本篇做法:

Step1:在 functions.php 內新增註冊函式

打開 functions.php,在裡面新增函式 footer_widgets_init() 並 add_action(),接著在裡面用 register_sidebar() 建立一個小工具。

function footer_widgets_init() {

    // Register the sidebar
    register_sidebar( array(
        'name'          => __( 'Footer1', 'textdomain' ),
        'id'            => 'footer-1',
        'description'   => __( 'Footer Widget', 'textdomain' ),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widgettitle">',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'footer_widgets_init' );

 

Step2:編輯小工具

接著就可以從外觀 > 小工具那邊找到剛剛新增的小工具區塊,顯示名稱會跟剛剛建立時定義的 Name 一樣

wp sidebar

 

Step3:在 html 插入區塊

接著在 wordpress 的 template 檔案加入這段,裡面的參數是跟著剛剛設定的 id

dynamic_sidebar( 'footer-1' ); 

設定好後,在頁面上就能看到小工具區塊會跟著設定後的樣子了,這時就可以自由編輯小工具區塊了。

 

Step4:更多區塊

如果想要設定更多不同的區塊,只要在 footer_widgets_init() 加入更多 register_sidebar() 就好了,之後就根據識別調整內容

function footer_widgets_init() {

    // Register the sidebar
    register_sidebar( array(
        'name'          => __( 'Footer1', 'textdomain' ),
        'id'            => 'footer-1',
        'description'   => __( 'Footer Widget', 'textdomain' ),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widgettitle">',
        'after_title'   => '</h2>',
    ) );
	register_sidebar( array(
        'name'          => __( 'Footer2', 'textdomain' ),
        'id'            => 'footer-2',
        'description'   => __( 'Footer Widget', 'textdomain' ),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widgettitle">',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'footer_widgets_init' );

藉由這個就可以很自由自訂小工具區塊,有在自己設定 WP 樣板的可以參考看看。

 

可以看官方文件了解更多 register_sidebar() 的用法。