首页 视频课程 主题开发课程第29章、子主题 WordPress创建子主题全过程

WordPress创建子主题全过程

2023-06-11 / 228阅

什么是子主题?

子主题(Child Theme)是WordPress主题的一个概念。它是基于另一个主题(Parent Theme)而创建的,即子主题是父主题的衍生版本。由于子主题基于父主题进行开发,因此它可以继承父主题的样式和功能,而无需对父主题进行修改。这样在更新父主题时,子主题的修改和自定义将不会丢失。

创建子主题的步骤

1. 创建子主题目录

首先,为子主题创建一个目录。在您的WordPress主题目录下,创建一个新目录并命名为您的子主题名称。

例如,如果您的父主题名称为"Twenty Twenty",则您的子主题目录可能应该命名为"twentytwenty-child"。

2. 创建子主题样式表

接下来,创建一个名为style.css的样式表文件,并将其保存在子主题目录下。此外,您需要在样式表文件中添加一个特定的主题头,以将子主题与其父主题关联。

在style.css文件中添加以下内容:

/*
 * Theme Name: Twenty Twenty Child
 * Theme URI: https://example.com/twenty-twenty-child/
 * Description: Child theme for the Twenty Twenty theme
 * Author: Your name
 * Author URI: https://example.com/
 * Template: twentytwenty
 * Version: 1.0.0
 * License: GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 * Tags: light,blog,right-sidebar,custom-background,custom-header,custom-menu,editor-style,featured-images,flexible-header,post-formats,stickey-post,theme-options,threaded-comments,translation-ready,one-column,Two-columns
*/ 

在主题头中,"Theme Name"、"Template"必须要填。Theme Name是您的子主题的名称,Template的值必须是您要创建子主题的父主题名称。警告:请勿将任何标签添加到主题头中。在主题头中添加太多标签会导致您的子主题不被WordPress识别。

3. 激活子主题

要启用您的新子主题,请转到WordPress管理后台中的外观 -> 主题页面。您现在应该看到您的子主题已显示在主题列表中。选择您的子主题,然后单击“激活”按钮。

4. 为子主题添加其他文件

在您的子主题目录中,您可以添加其他文件,如自定义页面模板、自定义函数等。

示例代码

以下是示例子主题中的style.css文件。

/*
 Theme Name: Twenty Twenty Child
 Theme URI: https://example.com/twenty-twenty-child/
 Description: Child theme for the Twenty Twenty theme
 Author: Your name
 Author URI: https://example.com/
 Template: twentytwenty
 Version: 1.0.0
 License: GNU General Public License v2 or later
 License URI: http://www.gnu.org/licenses/gpl-2.0.html
 Tags: light,blog,right-sidebar,custom-background,custom-header,custom-menu,editor-style,featured-images,flexible-header,post-formats,stickey-post,theme-options,threaded-comments,translation-ready,one-column,Two-columns
*/

/* Import the parent stylesheet */
@import url("../twentytwenty/style.css");

/* Custom styles below */

.entry-header {
  background: #f5f5f5;
  padding: 20px;
}

.entry-header h1 {
  margin: 0;
}

.entry-meta {
  display: none;
}

.entry-content p {
  font-size: 1.1em;
  line-height: 1.5;
}

a {
  color: #005090;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
} 

这个示例样式表文件引入它的父级样式表,并自定义了10个新样式。您可以在此基础上自定义自己的样式,去探索更多子主题的功能。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录