An Introduction to WordPress Theme Development: Building Your First Theme from Scratch

3-minute read
2026-03-11
2026-06-03
2,603
I earn commissions when you shop through the links below, at no additional cost to you.

Preparation Work and Environment Configuration

在开始编写代码之前,你需要一个合适的开发环境。本地开发环境可以让你在不影响线上网站的情况下进行测试和调试。推荐使用 XAMPP、MAMP 或 Local by Flywheel 等集成软件包,它们能一键安装 Apache、MySQL/MariaDB 和 PHP。

确保你的 PHP 版本在 7.4 或以上,这是 WordPress 官方推荐的最低版本。同时,你需要一个代码编辑器,如 Visual Studio Code、Sublime Text 或 PHPStorm,它们能提供语法高亮和代码提示功能,大大提高开发效率。

创建 WordPress 主题的基础结构

A WordPress theme is essentially a located in wp-content/themes/ 目录下的文件夹。这个文件夹的名字就是你的主题标识符,建议使用小写字母、数字和连字符,且不能有空格。例如,你可以创建一个名为 my-first-theme 的文件夹。

Within this folder, there must be at least two core files:style.css and index.phpstyle.css 不仅仅是样式表,它更重要的作用是提供主题的元信息,这些信息会显示在 WordPress 后台的“外观”->“主题”页面中。

编写主题信息头

In style.css 文件的顶部,你需要添加一个特定的注释块来定义主题信息。这是一个示例:

UltaHost WordPress Hosting
30-day refund guarantee, unlimited bandwidth and database usage, free DDoS protection; purchase for 3 years and get a discount of 50%.
/*
Theme Name: My First Theme
Theme URI: https://example.com/my-first-theme/
Author: Your Name
Author URI: https://example.com/
Description: 一个简洁、轻量级的入门级 WordPress 主题,用于学习主题开发。
Version: 1.0.0
License: GPL v2 or later
Text Domain: my-first-theme
*/

Among them,Text Domain 用于国际化(多语言支持),它必须与你的主题文件夹名称一致。index.php 文件则是主题的默认模板文件,是所有页面的后备模板。最初,你可以先在其中写入简单的 HTML 结构来测试。

核心模板文件与模板层次结构

WordPress 使用一套名为“模板层次结构”的规则来决定对于特定的页面请求,应该使用哪个模板文件来渲染。理解这个结构是主题开发的关键。其核心思想是:WordPress 会从最具体的模板文件开始寻找,如果找不到,则回退到更通用的文件,最终回退到 index.php

Recommended Reading Introduction to WordPress Theme Development: Building Your First Custom Theme from Scratch

常用模板文件及其用途

  • header.php: 网站的页头部分,通常包含 `` 区域、网站标识和主导航。
  • footer.php: 网站的页脚部分,通常包含版权信息、辅助链接等。
  • sidebar.php: 侧边栏区域。
  • index.php: 主模板,作为所有页面的最终后备。
  • single.phpUsed to display a single blog post.
  • page.php: 用于显示单个页面(如“关于我们”、“联系”)。
  • archive.php: 用于显示文章归档列表(如分类、标签、作者、日期归档)。
  • front-page.php: 用于定义网站首页(如果设置了一个静态页面作为首页)。
  • home.php: 用于显示博客文章索引页(如果设置了静态首页,这个模板显示最新的文章列表)。
  • 404.php: 用于显示“404 未找到”错误页面。
  • search.php: 用于显示搜索结果。
  • functions.php: 这不是一个模板文件,而是主题的功能文件,用于添加功能、注册菜单、侧边栏等。

Template tags and loops

在模板文件中,你会频繁使用“模板标签”。这些是 WordPress 提供的 PHP 函数,用于输出动态内容,如 bloginfo('name') Output the website title.the_title() 输出文章标题。

最核心的概念是“WordPress 循环”。它是一个 PHP 代码结构,用于检查当前页面是否有文章(或文章列表)需要显示,并循环输出它们。一个最基本的循环如下:

<h2></h2>
    <div class="entry-content">
        \n
    </div>

    <p><?php _e( 'Sorry, no posts matched your criteria.', 'my-first-theme' ); ?></p>

这段代码的意思是:如果有文章,就循环(while)每一篇,在循环中显示文章标题和内容;如果没有文章,则显示一条错误信息。`_e()` 是一个用于国际化的翻译函数。

Theme Features and Style Integration

functions.php 是你的主题的“大脑”,所有不属于模板渲染的核心功能都应在此添加。这个文件在主题初始化时被自动加载。

Registering for the Topic Feature

In functions.php 中,你可以通过 WordPress 提供的各种“钩子”(Hooks,如动作钩子和过滤器钩子)来扩展功能。首先,通常需要声明主题对某些功能的支持。例如,添加文章缩略图(特色图像)和菜单支持:

hosting.com Shared Hosting
High performance with AMD EPYC CPUs, NVMe SSD storage and LiteSpeed, 24/7, 24x7 expert in-house support, advanced security measures including SSL, brute force, malware and DDoS protection, savings of up to 73%
<?php
function my_first_theme_setup() {
    // 让主题支持文章和页面使用“特色图像”
    add_theme_support( 'post-thumbnails' );

// 注册导航菜单位置
    register_nav_menus( array(
        'primary' => __( 'Primary Menu', 'my-first-theme' ),
        'footer'  => __( 'Footer Menu', 'my-first-theme' ),
    ) );

// 让 WordPress 管理文档标题标签
    add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'my_first_theme_setup' );
?>

`add_action()` 将你的函数 my_first_theme_setup 挂载到 WordPress 的 after_setup_theme 这个动作钩子上,确保它在合适的时机执行。

Introducing styles and scripts

现代主题应该将样式表(CSS)和 JavaScript 文件正确地通过 wp_enqueue_style() and wp_enqueue_script() 函数加入队列,而不是直接在模板文件中写 `` 或 `` 标签。这样做的好处是管理依赖、避免重复加载、并遵循 WordPress 的最佳实践。

function my_first_theme_scripts() {
    // 引入主样式表
    wp_enqueue_style( 'my-first-theme-style', get_stylesheet_uri() );

// 引入自定义 JavaScript 文件
    wp_enqueue_script( 'my-first-theme-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_first_theme_scripts' );

`get_stylesheet_uri()` 指向你的 style.css 文件,`get_template_directory_uri()` 返回当前主题目录的 URL。

Recommended Reading An Introduction to WordPress Theme Development: Building Your Custom Theme from Scratch

构建页面布局与模板部件

一个标准的网页通常由页头、主体内容和页脚组成。WordPress 鼓励你将可重用的部分拆分成独立的文件,然后在主模板中通过特定的函数引入。

Splitting template components

Create header.phpfooter.php and sidebar.php. In header.php 中,你需要包含完整的 `` 部分,并以一个明显的头部容器(如 `` 标签)结束。在 footer.php 中,通常以 `` 和 `` 标签结束。

InterServer Shared Hosting
Shared hosting $2.50 USD per month , first month $0.1 USD promo code tryinterserver, 461 cloud apps scripts, one click install.

组装完整页面

在页面模板(如 index.phpsingle.php)中,你可以使用以下函数来引入这些部件:

<?php get_header(); ?>

<main id="primary" class="site-main">
    <?php
    // 这里放置 WordPress 循环
    if ( have_posts() ) :
        while ( have_posts() ) : the_post();
            // 内容输出
        endwhile;
    endif;
    ?>
</main>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

`get_header()`、`get_sidebar()` 和 `get_footer()` 会分别加载对应的模板文件。你还可以使用 `get_template_part()` 函数来加载更细粒度的模板部件,例如 `get_template_part( 'template-parts/content', 'page' );` 会尝试加载 template-parts/content-page.php 文件,如果不存在则加载 template-parts/content.php。这极大地提高了代码的复用性和可维护性。

summarize

从零开始构建一个 WordPress 主题是一个系统性的学习过程。你首先需要建立正确的本地开发环境并理解主题的基础文件结构。核心在于掌握 WordPress 的模板层次结构,它决定了不同内容如何被渲染。通过 functions.php 文件,你可以为主题添加强大的功能和特性,并遵循最佳实践来管理样式与脚本。最后,通过将页面拆分为页头、页脚、侧边栏等模板部件,并使用 WordPress 提供的函数将它们组装起来,你可以创建出结构清晰、易于维护的主题代码。遵循这些步骤,你不仅能够创建出你的第一个主题,更能为未来开发更复杂、更专业的项目打下坚实的基础。

Recommended Reading Introduction to WordPress Theme Development: Building Your First Custom Theme from Scratch

FAQ Frequently Asked Questions

开发 WordPress 主题必须掌握 PHP 吗?

是的,PHP 是 WordPress 的核心编程语言。主题的模板文件(如 index.phppage.php) and function filesfunctions.php)都是 PHP 文件。你需要掌握 PHP 的基础语法、条件判断、循环以及函数的使用,才能动态地输出和操作 WordPress 中的数据。

主题开发中,`page.php` 和 `front-page.php` 有什么区别?

page.php 用于渲染 WordPress 中创建的单个“页面”(Page),例如“关于我们”、“联系方式”等。而 front-page.php 是专门用于渲染网站“首页”的模板。在 WordPress 后台的“设置”->“阅读”中,如果你选择“一个静态页面”,并将“首页”设置为某个页面,那么 WordPress 就会优先使用 front-page.php 来显示这个页面。如果 front-page.php 不存在,则会使用 page.php

为什么推荐使用 `wp_enqueue_style()` 来加载 CSS,而不是直接在 HTML 中写 `` 标签?

utilization wp_enqueue_style() 是 WordPress 官方推荐的方法。它能确保样式表只被加载一次,即使多个插件或主题部分引用了同一个文件。它可以方便地处理样式表的依赖关系(例如,你的样式依赖于某个基础框架)。此外,它还能与缓存和插件更好地兼容,并允许子主题轻松地覆盖父主题的样式。

How can I make my theme support multiple languages (internationalization)?

让主题支持多语言主要涉及两个步骤。首先,在主题的所有文本字符串中,使用 WordPress 的翻译函数,如 ()_e() Or esc_html()And specify their locations. style.css Define in Chinese Text DomainFor example:_e( 'Hello World', 'my-first-theme' )。其次,使用 Poedit 这类工具,扫描你的主题代码,生成 .pot Template files, which translators can use to create translations in different languages. .po And the compiled version .mo Files: Place the language files in the theme directory. /languages/ 目录下,WordPress 会根据网站的语言设置自动加载对应的翻译。