WordPress 主题制作终极指南:从零开始打造你的专属主题

制作 WordPress 主题是深入理解 WordPress 工作原理、提升开发技能的最佳方式,本教程将引导你完成一个名为 MyTheme 的简单、现代主题的制作。

wordpress主题模板制作教程
(图片来源网络,侵删)

第一部分:准备工作与基础概念

在开始编码之前,我们需要了解一些基本概念和准备工作。

什么是 WordPress 主题? 主题是控制网站外观和感觉的一组文件,它决定了网站的布局、颜色、字体和设计元素,WordPress 主题不改变网站的内容,只改变内容的呈现方式。

准备工作

  • 本地开发环境: 强烈建议在本地电脑上搭建 WordPress 环境,这样不会影响线上网站,推荐使用:
    • Local by Flywheel: (最推荐,专为 WordPress 设计,一键安装)
    • XAMPP/MAMP: (经典的本地服务器环境,需要手动配置 WordPress)
  • 代码编辑器: 如 VS Code、Sublime Text、Atom 等,它们提供语法高亮、代码提示等功能,能极大提升开发效率。
  • 浏览器开发者工具: 用于调试 HTML、CSS 和 JavaScript,是前端开发的必备工具。

WordPress 主题的基本结构 一个标准的 WordPress 主题至少需要包含以下文件:

wordpress主题模板制作教程
(图片来源网络,侵删)
my-theme/
├── index.php          (主模板文件,当没有其他特定模板时使用)
├── style.css          (主题样式表,必须包含主题头部信息)
├── functions.php      (主题功能函数文件)
└── /images/           (存放图片的文件夹)

更完整的主题通常还会包含:

  • header.php (网站头部模板)
  • footer.php (网站底部模板)
  • sidebar.php (侧边栏模板)
  • single.php (文章单页模板)
  • page.php (页面单页模板)
  • archive.php (归档页模板)
  • search.php (搜索结果页模板)
  • php (404 错误页模板)
  • screenshot.png (主题预览图,300x225 像素)

第二部分:创建主题骨架

让我们动手创建主题的基本文件结构。

步骤 1:创建主题文件夹 在你的 WordPress 安装目录下的 wp-content/themes/ 文件夹中,创建一个新文件夹,命名为 my-theme

步骤 2:创建 style.css 文件 这是主题的“身份证”,必须包含特定的注释信息,在你的 my-theme 文件夹中创建 style.css 文件,并填入以下内容:

wordpress主题模板制作教程
(图片来源网络,侵删)
/*
Theme Name: MyTheme
Theme URI: https://example.com/my-theme
Author: Your Name
Author URI: https://example.com
Description: A simple and modern WordPress theme.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: my-theme
*/
  • Theme Name: (必须) 主题的显示名称。
  • Version: (必须) 主题的版本号。
  • 其他信息: 推荐填写,有助于主题的管理和分发。

步骤 3:激活你的主题 登录你的本地 WordPress 后台,进入 外观 -> 主题,你应该能看到 "MyTheme" 并可以点击“激活”它,激活后,你的网站会变得非常简陋,因为只有一个空的 index.php


第三部分:构建主题模板文件

WordPress 使用一种叫做“模板层次结构”(Template Hierarchy)的规则来确定哪个文件来显示特定类型的内容,显示一篇文章会优先使用 single.php,如果没有,则回退到 index.php

步骤 1:创建 header.php 这个文件将包含网站的 <head> 部分和页面顶部的导航栏等。

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); // 必须调用,用于加载 WordPress 插入的 CSS 和 JS ?>
</head>
<body <?php body_class(); ?>>
<header>
    <div class="container">
        <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a>
        <nav>
            <?php
            wp_nav_menu( array(
                'theme_location' => 'primary', // 我们稍后会注册这个菜单位置
                'menu_class'     => 'nav-menu',
            ) );
            ?>
        </nav>
    </div>
</header>
<div id="content" class="site-content">

步骤 2:创建 footer.php 这个文件包含页面底部的内容。

</div><!-- #content -->
<footer>
    <div class="container">
        <p>&copy; <?php echo date('Y'); ?> <?php bloginfo('name'); ?>. All Rights Reserved.</p>
    </div>
</footer>
<?php wp_footer(); // 必须调用,用于加载 WordPress 插入的 JS 等脚本 ?>
</body>
</html>

步骤 3:创建 index.php 这是我们的主模板文件,它将组合 header.phpfooter.php,并在中间显示博客文章列表。

<?php get_header(); ?>
<main id="main" class="site-main" role="main">
    <?php if ( have_posts() ) : ?>
        <?php while ( have_posts() ) : the_post(); ?>
            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <header class="entry-header">
                    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                    <div class="entry-meta">
                        <?php echo get_the_date(); ?> by <?php the_author(); ?>
                    </div>
                </header>
                <div class="entry-content">
                    <?php the_excerpt(); // 显示文章摘要 ?>
                </div>
                <footer class="entry-footer">
                    <a href="<?php the_permalink(); ?>">Read More</a>
                </footer>
            </article>
        <?php endwhile; ?>
        <!-- 分页导航 -->
        <div class="pagination">
            <?php the_posts_pagination(); ?>
        </div>
    <?php else : ?>
        <p><?php _e( 'Sorry, no posts matched your criteria.', 'my-theme' ); ?></p>
    <?php endif; ?>
</main>
<?php get_footer(); ?>
  • get_header(): 加载 header.php 文件。
  • get_footer(): 加载 footer.php 文件。
  • have_posts() & the_post(): WordPress 循环的核心,用于遍历文章。
  • the_permalink(): 获取文章的永久链接。
  • the_title(): 获取文章标题。
  • the_excerpt(): 获取文章摘要。
  • the_posts_pagination(): 生成标准的分页导航。

步骤 4:创建 single.php 这个文件用于显示单篇文章的完整内容,复制 index.php 的内容,然后修改一下:

<?php get_header(); ?>
<main id="main" class="site-main" role="main">
    <?php while ( have_posts() ) : the_post(); ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <header class="entry-header">
                <h1><?php the_title(); ?></h1>
                <div class="entry-meta">
                    <?php echo get_the_date(); ?> by <?php the_author(); ?>
                </div>
            </header>
            <div class="entry-content">
                <?php the_content(); // 显示文章完整内容,并处理 <!--more--> 标签 ?>
            </div>
            <footer class="entry-footer">
                <?php the_tags( 'Tags: ', ', ', '<br>' ); ?>
            </footer>
        </article>
    <?php endwhile; ?>
</main>
<?php get_sidebar(); // 加载侧边栏,我们稍后创建 ?>
<?php get_footer(); ?>

注意这里我们使用了 the_content() 而不是 the_excerpt()

步骤 5:创建 page.php 用于显示“页面”(如“关于我们”、“联系我们”),它和 single.php 非常相似,但不需要文章评论和标签。

<?php get_header(); ?>
<main id="main" class="site-main" role="main">
    <?php while ( have_posts() ) : the_post(); ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <header class="entry-header">
                <h1><?php the_title(); ?></h1>
            </header>
            <div class="entry-content">
                <?php the_content(); ?>
            </div>
        </article>
    <?php endwhile; ?>
</main>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

第四部分:添加样式和功能

现在我们的主题结构已经搭好,但看起来很丑,让我们来美化它,并添加一些 WordPress 特有的功能。

步骤 1:创建 functions.php 这个文件是主题的“大脑”,用于添加功能。

<?php
/**
 * 主题功能文件
 */
// 1. 添加主题支持
function my_theme_setup() {
    // 添加特色图片(缩略图)支持
    add_theme_support( 'post-thumbnails' );
    // 添加 HTML5 标签支持
    add_theme_support( 'html5', array( 'comment-list', 'comment-form', 'search-form', 'gallery', 'caption' ) );
    // 注册导航菜单
    register_nav_menus( array(
        'primary' => '主导航菜单',
    ) );
    // 添加自定义 Logo 支持 (WordPress 4.5+)
    add_theme_support( 'custom-logo', array(
        'height'      => 100,
        'width'       => 400,
        'flex-height' => true,
        'flex-width'  => true,
        'header-text' => array( 'site-title', 'site-description' ),
    ) );
}
add_action( 'after_setup_theme', 'my_theme_setup' );
// 2. 注册和加载样式表
function my_theme_enqueue_styles() {
    // 加载父主题样式(如果有的话,这里我们不需要)
    // wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    // 加载主题主样式表
    wp_enqueue_style( 'my-theme-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
// 3. 注册和加载 JavaScript
function my_theme_enqueue_scripts() {
    // 加载主题的 main.js 文件
    wp_enqueue_script( 'my-theme-script', get_template_directory_uri() . '/js/main.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );

步骤 2:创建一个简单的 CSS 文件my-theme 文件夹中创建一个 css 文件夹,并在其中创建 style.css

/* css/style.css */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    line-height: 1.6;
    margin: 0;
    background-color: #f4f4f4;
    color: #333;
}
.container {
    max-width: 1100px;
    margin: 0 auto;
    padding: 0 20px;
}
header {
    background: #333;
    color: #fff;
    padding: 1rem 0;
}
header a {
    color: #fff;
    text-decoration: none;
    font-size: 1.5rem;
    font-weight: bold;
}
.nav-menu {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
}
.nav-menu li {
    margin-left: 20px;
}
.site-content {
    padding: 2rem 0;
}
article {
    background: #fff;
    margin-bottom: 2rem;
    padding: 2rem;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.entry-header h2, .entry-header h1 {
    margin-top: 0;
}
.entry-content a {
    color: #0073aa;
}
.pagination {
    text-align: center;
    margin: 2rem 0;
}

步骤 3:创建 sidebar.php 侧边栏通常包含小工具。

<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>
    <aside id="secondary" class="widget-area" role="complementary">
        <?php dynamic_sidebar( 'sidebar-1' ); ?>
    </aside><!-- #secondary -->
<?php endif; ?>

步骤 4:在 functions.php 中注册侧边栏 回到 functions.php,在 my_theme_setup 函数中添加以下代码:

// 在 register_nav_menus 之后添加
// 注册侧边栏
function my_theme_widgets_init() {
    register_sidebar( array(
        'name'          => '主侧边栏',
        'id'            => 'sidebar-1',
        'description'   => '添加一些小工具到这里。',
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'my_theme_widgets_init' );

步骤 5:添加自定义 Logo 支持 为了让自定义 Logo 功能生效,我们需要修改 header.php,找到 <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a> 这一行,将它替换为:

<?php if ( has_custom_logo() ) : ?>
    <?php the_custom_logo(); ?>
<?php else : ?>
    <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a>
<?php endif; ?>

第五部分:完善与进阶

现在你的主题已经有基本的功能和样式了,让我们做最后的完善和一些进阶操作。

步骤 1:添加 search.phpsearchform.php search.php 用于显示搜索结果,searchform.php 用于创建搜索表单。

  • 创建 searchform.php:

    <form role="search" method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
        <input type="search" placeholder="搜索..." value="<?php echo get_search_query(); ?>" name="s" id="s" />
        <button type="submit">搜索</button>
    </form>
  • 创建 search.php: 复制 index.php 的内容,然后在循环开始前可以添加一个搜索结果的提示。

    <?php get_header(); ?>
    <main id="main" class="site-main" role="main">
        <header class="page-header">
            <h1 class="page-title">
                <?php printf( '搜索结果: %s', '<span>' . get_search_query() . '</span>' ); ?>
            </h1>
        </header>
        <?php if ( have_posts() ) : ?>
            // ... 这里是和 index.php 一样的循环代码 ...
        <?php else : ?>
            <p><?php _e( 'Sorry, nothing matched your search. Please try again.', 'my-theme' ); ?></p>
        <?php endif; ?>
    </main>
    <?php get_sidebar(); ?>
    <?php get_footer(); ?>

步骤 2:添加 archive.php 归档页用于显示按分类、标签、日期等归类的文章列表,它通常和 index.php 很像。

你可以先复制 index.php 并重命名为 archive.php,在循环开始前添加一个标题,显示当前归档的类型。

<?php get_header(); ?>
<main id="main" class="site-main" role="main">
    <header class="page-header">
        <?php
            the_archive_title( '<h1 class="page-title">', '</h1>' );
            the_archive_description( '<div class="archive-description">', '</div>' );
        ?>
    </header>
    <?php if ( have_posts() ) : ?>
        // ... 这里是和 index.php 一样的循环代码 ...
    <?php else : ?>
        <p><?php _e( 'Sorry, no posts matched your criteria.', 'my-theme' ); ?></p>
    <?php endif; ?>
</main>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

步骤 3:添加 php 当用户访问一个不存在的页面时,这个文件会被加载。

<?php get_header(); ?>
<div class="page-not-found">
    <h1>404 - 页面未找到</h1>
    <p>抱歉,您访问的页面不存在,请尝试搜索或返回首页。</p>
    <?php get_search_form(); ?>
</div>
<?php get_footer(); ?>

第六部分:总结与后续

恭喜!你已经成功创建了一个功能完整的 WordPress 主题,这个主题包含了:

  • 响应式的基本布局
  • 头部和底部模板
  • 文章、页面、搜索、归档和 404 页面
  • 自定义导航菜单和侧边栏
  • 特色图片和自定义 Logo 支持

后续可以学习的内容:

  1. 模板部分: 学习使用 get_template_part() 来复用代码块,例如创建 content.php 来存放文章的通用结构。
  2. 自定义izer (自定义器): 学习使用 WordPress 自定义器 API,让用户可以在后台实时修改颜色、背景、Logo 等。
  3. Widgets API: 创建自己的小工具,让用户可以更灵活地布局侧边栏。
  4. Options Framework: 学习使用像 ACF (Advanced Custom Fields) 这样的插件,为文章和页面添加自定义字段。
  5. 安全性: 学习 WordPress 安全最佳实践,如数据转义 (esc_html, esc_url) 和非空检查。

制作主题是一个不断学习和实践的过程,从模仿开始,逐步加入自己的创意和功能,你会越来越熟练,祝你开发愉快!