更新日期:2021-12-09

官方建議盡量避免修改佈景主題,因為該佈景做了更新的話,你的修改內容都會被覆蓋掉,因此還是建議採用新增一個隸屬該佈景主題的子佈景主題,是最佳解決方案,底下教你如何建立子佈景主題。

建立子佈景主題的資料夾

第一步驟是在 wp-content/themes 建立一個資料夾,資料夾名稱的命名方式,依照原有的佈景主題資料夾名稱,後面加上 -child,例如:我們要幫 twentytwenty 佈景主題,他的子佈景主題資料夾就可以命名為 twentytwenty-child,接下來我們要在這個資料夾下建立所需要的檔案。

建立樣式表檔案 style.css

進入到剛剛建立的資料夾下,新增一個 style.css 檔案,檔案開頭內容請加上以下說明

/*
  Theme Name:   Twentytwenty Child
  Description:  Twentytwenty Child Theme
  Author:       Simon
  Template:     twentytwenty
  Version:      1.0.0
  Text Domain:  twentytwentychild
*/

/* 以下開始填寫你的 css */

Theme Name:佈景名稱必填,請命名為你方便記憶的文字。
Template:也是必填,請填寫父佈景主題目錄的名稱。
Text Domain:一般也是會根據父佈景的 Text Domain 命名,加上 child 字樣即可。

建立 functions.php

接著也在資料夾下建立 functions.php 檔案(這個用途不再解釋,相信網路上也有很多說明)。但因為父佈景主題的 style.css 可能會也可能不會被自動載入,所以我們要先開啟父佈景主題的 functions.php,判斷是哪一種,再來寫語法。

1. 會自動載入父佈景主題的 style.css:

wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/style.css', array(), wp_get_theme()->get( 'Version' ) );

從上方 wp_enqueue_style 來看,如果看到 get_template_directory() 或是 get_template_directory_uri(),則這個父佈景主題的 style.css 會被自動載入。因此只需要寫載入子佈景主題的 style.css,程式碼如下:

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );

function my_theme_enqueue_styles() {
    wp_enqueue_style( 'twenty-twenty-one-child-style', get_stylesheet_uri(),
        array( 'twenty-twenty-one-style' ),
        wp_get_theme()->get('Version')
    );
}

2. 不會載入父佈景主題的 style.css:

wp_enqueue_style( 'twentynineteen-style', get_stylesheet_uri(), array(), wp_get_theme()->get( 'Version' ) );

從上方 wp_enqueue_style 來看,如果看到 get_stylesheet_directory() 或是 get_stylesheet_directory_uri(),需要寫先載入父佈景主題的 style.css,再載入子佈景的 style.css,程式碼如下:

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );

function my_theme_enqueue_styles() {
    $parenthandle = 'twentynineteen-style';
    $theme = wp_get_theme();
    wp_enqueue_style( $parenthandle, get_template_directory_uri() . '/style.css',
        array(),
        $theme->parent()->get('Version')
    );
    wp_enqueue_style( 'twentynineteen-child-style', get_stylesheet_uri(),
        array( $parenthandle ),
        $theme->get('Version')
    );
}

( 這邊要注意載入子佈景時,要先載入父佈景的 style.css’ );

子佈景的 Textdomain

function twentyfifteenchild_theme_setup() {
    load_child_theme_textdomain( 'twentyfifteenchild', get_stylesheet_directory() . '/languages' );
}
add_action( 'after_setup_theme', 'twentyfifteenchild_theme_setup' );

取代父佈景主題其他程式檔案

在子佈景主題中,除了剛剛介紹的 style.css 和 functions.php 這兩個檔案不會覆蓋父佈景主題的檔案外。其他只要檔案名稱相同的,都會去覆蓋了父佈景主題的檔案。舉例來說,若是我們想要修改 header 程式,我們必須先從父佈景主題,複製 header.php 到子佈景主題內,然後再去子佈景主題編修這個新檔案才對。

上傳子佈景主題

都完成設計之後,請將子佈景主題的資料夾壓縮成 zip 檔案,然後到後台「佈景主題」->「安裝佈景主題」,點擊上傳按鈕,然後記得啟用它即可。

補充

get_template_directory() 指向是父主題目錄
get_stylesheet_directory() 指向子主題目錄