WordPress child theme 子主題
PHP WordPress

WordPress child theme 子主題

商業,創業,業務,職涯,美食,葡萄酒,閱讀,網路科技。
從 Larry 創業以及商業的經驗,希望以白話的口吻,介紹給大家這個商業的世界。
FB粉絲頁 Larry的午茶時光
IG Larry的午茶時光 歡迎大家追蹤~

圖片來源 https://wordpress.org

https://developer.wordpress.org/themes/advanced-topics/child-themes/
https://docs.woocommerce.com/document/set-up-and-use-a-child-theme/

一個 child theme (子主題) 至少要加三部分

1. child theme 的資料夾

如官方文件所述,如果你想要幫
wp-content/themes/twentyfifteen 加 child theme, 則資料夾是
wp-content/themes/twentyfifteen-child

加上 -child, 把它當做 coding convention.

2. style.css

twentyfifteen-child 來說,就是 wp-content/themes/twentyfifteen-child/style.css
一樣要加上 stylesheet header, 注意新增一個 Template 欄位,例如
Template: twentyfifteen 指定你的 parent 是 twentyfifteen

3. functions.php

子主題的 functions.php 會「先於」父主題的 functions.php 被執行 (兩者都會執行)

接著要引用 parent 的 style.css, 官方文件提到在 child theme 使用 @import 是「以前」方法了,目前建議的方法是在子主題的 functions.php 加上

<?php
function my_theme_enqueue_styles() {

    $parent_style = 'parent-style';

    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_style ),
        wp_get_theme()->get('Version')
    );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>

注意

a. 去父主題的 functions.php 找到 wp_enqueue_style, 一般來說,主題需要告訴 WP 核心去引用 css, wp_enqueue_style 的第一個參數就是識別字串 (官方文件叫 $handle), 把這個識別字串記住,上方的 $parent_style 改成這個識別字串。

b. 檢查父主題 functions.php 是否已有幫子主題 wp_enqueue_style 的 code, 檢查 wp_enqueue_style 和 is_child_theme. 如果有的話,子主題連 functions.php 都不用加 (當然如果你要客製化 functions.php 的話還是要加)

c. 承 b, 如果父主題「沒有」幫子主題 wp_enqueue_style 的 code, 則需要上方附的程式碼,否則父主題的 style.css 不會被引用到 html head.

d. 如果你的 child theme 不只有 style.css, 要 review 所有 css 檔案的相依性,照順序 wp_enqueue_style

到目前為止,你的後台主題面板應該已經看得到你的 child theme, 並可以啟用。如果你想換的不只是 css, 還需要換 template. 那直接在 child theme 新增一樣檔名的 template php 即可。

官方文件有提到,要改 functions.php 時,建議新增 child theme, 在 child theme functions.php 裡 orverwrite 你要改的 function, 因為當主題升級時,functions.php 會被覆寫掉。要注意的是,你的父主題的 function 要 “pluggable” (用 function_exists 包住)

官方文件附了一個寫 <link> 的範例,程式上沒有特殊之處,但概念上 WordPress 有點像是在 functions.php 裡做 templating.

最後有 child theme 時,get_template_directory() return 的是父主題的資料夾,要拿到子主題的路徑,請用 get_stylesheet_directory()

商業,創業,業務,職涯,美食,葡萄酒,閱讀,網路科技。
從 Larry 創業以及商業的經驗,希望以白話的口吻,介紹給大家這個商業的世界。
FB粉絲頁 Larry的午茶時光
IG Larry的午茶時光 歡迎大家追蹤~