WordPress 的子主题 (Child Themes) 功能,可继承父主题的所有功能与样式,并在此基础上进行修改以及添加功能与样式,且不影响父主题的更新。
创建子主题
在 WordPress 主题文件夹 (wp-content/themes) 中,必须同时包含父主题文件夹,以及新增的子主题文件夹。
如:
- mookwai (父主题)
- mookwai-child (子主题,名称可自己设定)
子主题文件夹中必须包含 style.css 文件,并在头部创建主题描述内容
/*
Theme Name: MooKwai Custom
Theme URI: https://mookwai.puji.design
Author: PUJI Design
Author URI: https://puji.design
Description: MooKwai Website Theme
Template: MooKwai
Tested up to: 5.9
Requires PHP: 5.6
Version: 0.1
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: lined
Tags: one-column, custom-colors, custom-menu, custom-logo, editor-style, featured-images, full-site-editing, block-patterns, rtl-language-support, sticky-post, threaded-comments
MooKwai WordPress Theme, (C) 2022 puji.design
MooKwai is distributed under the terms of the GNU GPL.
*/
其中 Template 即是让该子主题指定其父主题的名称。
这样,一个子主题就创建完成。
编辑子主题
子主题中除必须包含的 style.css 文件外,还可自定义更多的新的文件,这些新的文件会在原有的基础上新增功能或覆盖原来的内容。
在子主题中如果需要引用子主题中的其他文件,可使用 get_stylesheet_directory() 函数。
require_once( get_stylesheet_directory(). '/my_included_file.php' );
启用子主题
一切准备就绪,将子主题的整个文件夹上传到网站的主题文件夹下,然后在后台控制面板中 “外观” 下启用该子主题即可。