2026-04-02 23:12:36 +08:00

92 lines
3.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 为WordPress创建子主题
createTime: 2021/09/16
tags:
- Wordpress
categories:
- 随记
---
## 子主题
- 父主题是一个完整的主题,其中包括所有必需的 WordPress 模板文件和主题工作所需的文件资源。所有主题(不包括子主题)都可以被认为是父主题。
- 子主题可以继承父主题所有功能和外观,但可用于对主题的任何部分进行修改。自定义子主题与父主题的文件是分开的,升级父主题时不会影响对站点所做的修改。
**如果需要进行大量的样式、功能修改,则不推荐使用子主题**
## 创建子主题
找到`wp-content/themes`,记住父主题的**文件夹名称(注意不是主题名)**,这里以 kratos 为例。
1. 在 temes 目录下新建文件夹并进入,文件夹即为子主题路径。
```bash
mkdir kratos-yuany3721
cd kratos-yuany3721
```
2. 新建`style.css`文件并进行配置如下:
```css
/*
Theme Name: kratos-yuany3721
Theme URI: http://example.com
Description: kratos-yuany3721
Author: yuany3721
Author URI: http://example.com
Template: kratos
Version: 0.0.1
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
Text Domain: yyyy
*/
```
其中Theme Name 需要对 themes 目录内主题唯一Template 后写的是父主题的**文件夹名称**,其余各内容均非必填项。
3. 新建`functions.php`并进行配置。回到父主题查看`functions.php`
- 如果存在 get_template 函数,例如 get_template_directory()或者 get_template_directory_uri(),则如下配置 functions.php
```php
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'child-style', get_stylesheet_uri(),
array( 'parenthandle' ),
wp_get_theme()->get('Version') // this only works if you have Version in the style header
);
}
```
- 如果存在 get_stylesheet 函数,例如 get_stylesheet_directory()或 get_stylesheet_directory_uri(),则如下配置 functions.php
```php
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parenthandle = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
$theme = wp_get_theme();
wp_enqueue_style( $parenthandle, get_template_directory_uri() . '/style.css',
array(), // if the parent theme code has a dependency, copy it to here
$theme->parent()->get('Version')
);
wp_enqueue_style( 'child-style', get_stylesheet_uri(),
array( $parenthandle ),
$theme->get('Version') // this only works if you have Version in the style header
);
}
```
- 以本文 kratos 为例,配置如下:
```php
<?php
function my_theme_enqueue_styles() {
wp_enqueue_style( 'child-style', get_template_directory_uri().'/style.css' );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles');
```
4. 回到 WordPress 主题中查看,如果配置无误就会出现一个新的子主题,点击启用即可