主题开发文档

重构主题文件与组织

💡 云策文档标注

概述

本文档探讨了WordPress主题的文件结构和组织方式,强调从基本文件需求出发,通过分析Twenty Twelve主题示例,说明如何优化文件布局以提高可维护性。

关键要点

  • WordPress主题技术上仅需index.php和style.css两个文件,但实际开发中常包含多个文件,需合理组织以避免混乱。
  • 主题文件结构应基于功能划分,例如comments.php处理评论、image.php处理图像,文件名应清晰反映其用途。
  • 推荐将主要模板文件放在主题根目录,而JavaScript、语言文件、CSS和页面模板等资源放入各自文件夹中。
  • WordPress默认识别特定文件夹,如page-templates文件夹用于自定义页面模板(自3.4.0版本起),languages文件夹用于国际化翻译。

📄 原文内容

basics-theme-files-organization-01

Theme folder and file structure

While WordPress themes technically only require two files (index.php and style.css), they usually are made up of many files and can become quickly disorganized.

In the last section, Template Files, you set up your header.php, footer.php, page.php, home.php, and single.php files.

Let’s look at  the Twenty Twelve theme default themes as one example of good file structure and organization.  While this may be a bit overwhelming at first, let’s break it down.  Can you find the templates you just built?

basics-theme-files-organization-02

While there are still a lot of files, their names help provide a context of what they are.  Basically each file handles a feature of WordPress.  I.e. comments.php deals with how the theme will handle comments; image.php instructs the theme how to handle images, etc.  Don’t worry about adding these files unless you need them.

You can see that the main theme template files are in the theme’s root directory, while JavaScript, languages, CSS, and page template files are placed within their own folders.

At this time there are no required folders within a WordPress theme. However, WordPress does recognize the following folders by default:

Page templates folder

basics-theme-files-organization-03

The custom page templates, named page-templates (since: 3.4.0) allows for better organization of template files. Custom page template files placed in this folder are automatically recognized by WordPress.

Language folder

basics-theme-files-organization-04

If you wish to internationalize your theme so it’s usable in other languages, you can create a languages folder to contain translations.