主题开发文档

组织主题文件

💡 云策文档标注

概述

本文档介绍了如何有效组织WordPress主题文件,以避免混乱。通过分析默认主题(如Twenty Seventeen)的文件结构,提供了经典主题和块主题的组织建议。

关键要点

  • WordPress主题通常由多个文件组成,仅需index.php(经典主题)或index.html(块主题)和style.css作为基础。
  • 推荐使用文件夹结构来分类文件,例如将JavaScript、CSS和图像放在assets目录,模板部分放在template-parts子目录,核心功能函数放在inc目录。
  • 经典主题没有强制文件夹要求,而块主题必须将模板放在templates文件夹,模板部分放在parts文件夹。
  • style.css应位于主题根目录,而非CSS子目录内。
  • 国际化主题时,建议使用languages文件夹存放.pot和.mo文件,文件夹名称可自定义但需更新load_theme_textdomain()。

📄 原文内容

While WordPress themes technically only require two files (index.php in classic themes and index.html in block themes, and style.css), they usually are made up of many files. That means they can quickly become disorganized! This section will show you how to keep your files organized.

Theme folder and file structure

As mentioned previously, the default Twenty themes are some of the best examples of good theme development. For instance, here is how the Twenty Seventeen Theme organizes its file structure:

.
├── assets (dir)/
│   ├── css (dir)
│   ├── images (dir)
│   └── js (dir)
├── inc (dir)
├── template-parts (dir)/
│   ├── footer (dir)
│   ├── header (dir)
│   ├── navigation (dir)
│   ├── page (dir)
│   └── post (dir)
├── 404.php
├── archive.php
├── comments.php
├── footer.php
├── front-page.php
├── functions.php
├── header.php
├── index.php
├── page.php
├── README.txt
├── rtl.css
├── screenshot.png
├── search.php
├── searchform.php
├── sidebar.php
├── single.php
└── style.css

You can see that the main theme template files are in the root directory, while JavaScript, CSS, images are placed in assets directory, template-parts are placed in under respective subdirectory of template-parts and collection of  functions related to core functionalities are placed in inc directory.

There are no required folders in classic themes. In block themes, templates must be placed inside a folder called templates, and all template parts must be placed inside a folder called parts.

style.css should reside in the root directory of your theme not within the CSS directory.

Languages folder

It’s best practice to internationalize your theme so it can be translated into other languages. Default themes include the languages folder, which contains a .pot file for translation and any translated .mo files. While languages is the default name of this folder, you can change the name. If you do so, you must update <a href="https://developer.wordpress.org/reference/functions/load_theme_textdomain/">load_theme_textdomain()</a>.