杰瑞科技汇

如何制作WordPress主题?

WordPress 主题制作终极指南

本教程将带你从头开始,创建一个属于自己的、现代化、响应式的 WordPress 主题,我们将分步进行,确保你每一步都能理解。

如何制作WordPress主题?-图1
(图片来源网络,侵删)

第一部分:准备工作

在开始之前,你需要准备以下环境:

  1. 本地服务器环境:在你的电脑上搭建一个可以运行 PHP 和 MySQL 的环境。
    • 推荐工具Local (by Flywheel) 或 XAMPP,它们能一键安装 WordPress,非常适合开发者。
  2. 代码编辑器:一个强大的代码编辑器能让你事半功倍。
    • 推荐工具Visual Studio Code (免费且功能强大)、Sublime TextPhpStorm
  3. WordPress 安装:在你的本地服务器上安装一个全新的 WordPress,确保安装过程顺利,并可以访问后台。

第二部分:主题结构与“Hello World”

WordPress 主题本质上就是一个文件夹,里面包含了 PHP、CSS、JavaScript 和图片等文件。

步骤 1:创建主题文件夹

wp-content/themes/ 目录下,创建一个新的文件夹,我们将其命名为 my-first-theme

/wp-content/
└── /themes/
    └── /my-first-theme/  <-- 你的主题文件夹

步骤 2:创建 style.css 文件

这是 WordPress 主题的核心标识文件,没有它,WordPress 就不会识别你的主题,在你的 my-first-theme 文件夹中,创建一个 style.css 文件,并填入以下信息:

如何制作WordPress主题?-图2
(图片来源网络,侵删)
/*
Theme Name: My First Theme
Theme URI: https://example.com/my-first-theme
Author: Your Name
Author URI: https://example.com
Description: My very first 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-first-theme
*/
  • Theme Name: 必填,主题在 WordPress 后台显示的名称。
  • 其他信息: 建议填写,这能让你的主题看起来更专业。

去你的 WordPress 后台 > 外观 > 主题,你应该能看到 "My First Theme" 了,但点击后可能是一片空白,因为我们还没有添加任何模板文件。

步骤 3:创建 index.php 文件

index.php 是主题的主模板文件,当访问你的网站首页时,WordPress 就会调用这个文件,在 my-first-theme 文件夹中创建 index.php,并写入最简单的代码:

<?php
// 这是一句非常重要的“标签”,它告诉 WordPress 加载头部信息
get_header(); 
?>
    <div id="primary" class="content-area">
        <main id="main" class="site-main">
            <h1>Hello, World! 欢迎来到我的第一个 WordPress 主题!</h1>
            <?php
            // 如果你的网站有文章,就循环显示它们
            if ( have_posts() ) :
                while ( have_posts() ) : the_post();
                    // 显示文章标题
                    the_title( '<h2><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
                    // 显示文章内容摘要
                    the_excerpt();
                endwhile;
            else :
                // 如果没有文章,显示这段提示
                ?>
                <p><?php _e( '抱歉,没有找到任何内容。', 'my-first-theme' ); ?></p>
                <?php
            endif;
            ?>
        </main><!-- #main -->
    </div><!-- #primary -->
<?php
// 这句代码加载页脚信息
get_footer(); 
?>

刷新你的网站首页,你应该能看到 "Hello, World!" 和你发布的文章标题及摘要了!这就是一个最基本主题的雏形。


第三部分:模板文件详解

WordPress 使用一种名为 “模板层次结构” (Template Hierarchy) 的系统,它会根据当前请求的页面类型(首页、文章列表、单篇文章、页面等)来决定加载哪个 PHP 模板文件。

如何制作WordPress主题?-图3
(图片来源网络,侵删)

常用模板文件及其作用:

文件名 作用
index.php 主模板,所有其他模板文件都无法找到时的最终回退方案。
header.php 头部模板,包含 <head> 部分、网站 Logo、主导航菜单等。
footer.php 页脚模板,包含网站底部信息、版权声明、脚本加载等。
sidebar.php 侧边栏模板,包含小工具区域。
front-page.php 静态首页模板,当你在后台设置“首页显示为”为“静态页面”时,此文件会覆盖 index.php
home.php 博客首页模板,当你的首页显示最新文章列表时,此文件会覆盖 index.php
single.php 单篇文章模板,当用户点击一篇文章的链接时加载。
page.php 单页面模板,当用户访问一个“页面”(Page) 时加载。
archive.php 存档页模板,当访问分类目录、标签、作者或日期归档页面时加载。
search.php 搜索结果页模板,当用户进行搜索时加载。
php 404 错误页模板,当访问的页面不存在时加载。

如何创建和使用这些文件?

  1. 创建 header.php:

    <!DOCTYPE html>
    <html <?php language_attributes(); ?>>
    <head>
        <meta charset="<?php bloginfo( 'charset' ); ?>">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="profile" href="https://gmpg.org/xfn/11">
        <?php wp_head(); // **极其重要**!加载 WordPress 的头部钩子,用于插件和主题添加样式、脚本等 ?>
    </head>
    <body <?php body_class(); ?>>
        <div id="page" class="site">
            <header id="masthead" class="site-header">
                <div class="site-branding">
                    <?php
                    if ( has_custom_logo() ) {
                        the_custom_logo();
                    } else {
                        ?>
                        <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
                        <p class="site-description"><?php bloginfo( 'description' ); ?></p>
                        <?php
                    }
                    ?>
                </div><!-- .site-branding -->
                <nav id="site-navigation" class="main-navigation">
                    <?php
                    wp_nav_menu( array(
                        'theme_location' => 'primary', // 我们将在后面注册这个菜单位置
                        'menu_class'     => 'main-menu',
                    ) );
                    ?>
                </nav><!-- #site-navigation -->
            </header><!-- #masthead -->
  2. 创建 footer.php:

            <footer id="colophon" class="site-footer">
                <div class="site-info">
                    &copy; <?php echo date('Y'); ?> <?php bloginfo( 'name' ); ?>. All Rights Reserved.
                </div><!-- .site-info -->
            </footer><!-- #colophon -->
        </div><!-- #page -->
        <?php wp_footer(); // **极其重要**!加载 WordPress 的页脚钩子,用于加载脚本等 ?>
    </body>
    </html>
  3. 修改 index.php: 现在我们的 index.php 可以变得更简洁,因为它只负责内容区域,而头部和页脚都交给了 header.phpfooter.php


第四部分:引入样式和脚本

步骤 1:在 functions.php 中注册样式和脚本

functions.php 是主题的“功能中心”,它像一个插件,可以为主题添加各种功能,在 my-first-theme 文件夹中创建 functions.php,并添加以下代码:

<?php
/**
 * 主题功能设置
 */
// 1. 添加主题支持
function my_theme_setup() {
    // 添加特色图片支持
    add_theme_support( 'post-thumbnails' );
    // 注册导航菜单
    register_nav_menus( array(
        'primary' => '主导航菜单',
    ) );
    // 添加 HTML5 语义化标签支持
    add_theme_support( 'html5', array(
        'search-form', 'comment-form', 'comment-list', 'gallery', 'caption'
    ) );
}
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( 'main-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
// 3. 加载主题脚本
function my_theme_enqueue_scripts() {
    // 加载 main.js 文件
    wp_enqueue_script( 'main-script', get_template_directory_uri() . '/js/main.js', array(), '1.0', true );
    // 最后一个参数 `true` 表示将脚本加载到页脚
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
?>

解释:

  • add_theme_support(): 让你的主题支持 WordPress 的某些核心功能,如特色图片、自定义菜单等。
  • wp_enqueue_style(): 安全地加载 CSS 文件,我们加载了 style.css
  • wp_enqueue_script(): 安全地加载 JavaScript 文件。

步骤 2:创建并编写 main.css

为了让网站更好看,我们需要一个 CSS 文件,创建一个 css 文件夹,并在里面创建 main.css

/* css/main.css */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
    color: #333;
}
.site-header {
    background: #fff;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    padding: 1rem 0;
}
.site-branding a {
    text-decoration: none;
    color: #333;
}
.main-navigation ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
}
.main-navigation li {
    margin-left: 20px;
}
.content-area {
    max-width: 1200px;
    margin: 2rem auto;
    padding: 0 2rem;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
.site-main h2 a {
    text-decoration: none;
    color: #0066cc;
}
.site-main h2 a:hover {
    text-decoration: underline;
}
.site-footer {
    text-align: center;
    padding: 2rem;
    margin-top: 2rem;
    background: #333;
    color: #fff;
}

你的网站应该已经应用上了这些基本样式,看起来像一个真正的网站了。


第五部分:循环与函数

The Loop (主循环) 是 WordPress 的核心。if ( have_posts() ) : while ( have_posts() ) : the_post(); 就是循环的开始和结束。

single.php 中,我们可以创建一个更详细的单篇文章模板:

<?php get_header(); ?>
    <div id="primary" class="content-area">
        <main id="main" class="site-main">
            <?php
            while ( have_posts() ) : the_post();
                ?>
                <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                    <header class="entry-header">
                        <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
                    </header><!-- .entry-header -->
                    <div class="entry-content">
                        <?php
                        // 显示文章完整内容
                        the_content( sprintf(
                            wp_kses(
                                /* translators: %s: Name of current post. */
                                __( 'Continue reading %s <span class="meta-nav">&rarr;</span>', 'my-first-theme' ),
                                array( 'span' => array( 'class' => array( 'meta-nav' ) ) )
                            ),
                            the_title( '<span class="screen-reader-text">"', '"</span>', false )
                        ) );
                        wp_link_pages( array(
                            'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'my-first-theme' ),
                            'after'  => '</div>',
                        ) );
                        ?>
                    </div><!-- .entry-content -->
                    <footer class="entry-footer">
                        <?php my_first_theme_entry_footer(); // 我们将在 functions.php 中创建这个函数 ?>
                    </footer><!-- .entry-footer -->
                </article><!-- #post-<?php the_ID(); ?> -->
                <?php
                // 如果评论是开启的,加载评论模板
                if ( comments_open() || get_comments_number() ) :
                    comments_template();
                endif;
            endwhile; // End of the loop.
            ?>
        </main><!-- #main -->
    </div><!-- #primary -->
<?php get_sidebar(); // 加载侧边栏 ?>
<?php get_footer(); ?>

常用模板函数:

  • the_title(): 显示文章标题。
  • the_permalink(): 显示文章链接。
  • the_content(): 显示文章内容。
  • the_excerpt(): 显示文章摘要。
  • the_post_thumbnail(): 显示文章的特色图片。
  • the_author(): 显示文章作者。
  • the_time(): 显示文章发布时间。
  • the_category(): 显示文章分类。
  • the_tags(): 显示文章标签。

第六部分:响应式设计与主题定制

响应式设计

使用 CSS Media Queries 可以让你的网站在不同设备上都能良好显示。

css/main.css 末尾添加:

/* 响应式设计 */
@media screen and (max-width: 768px) {
    .content-area {
        padding: 0 1rem;
    }
    .main-navigation ul {
        flex-direction: column;
        align-items: flex-start;
    }
    .main-navigation li {
        margin-left: 0;
        margin-bottom: 10px;
    }
}

主题定制器

functions.php 中的 add_theme_support( 'custom-logo' ); 已经添加了自定义 Logo 支持,你还可以添加更多:

// 在 my_theme_setup 函数中添加
add_theme_support( 'custom-background' ); // 自定义背景
add_theme_support( 'title-tag' ); // 自动管理 <title> 标签

用户可以在 WordPress 后台 > 外观 > 自定义 中进行这些设置了。


第七部分:最终检查与发布

  1. 检查所有页面:确保首页、单篇文章、页面、分类页、搜索页、404 页等都能正常显示。
  2. 安装插件测试:安装一些常用插件(如 SEO 插件、缓存插件),看看是否与你的主题冲突。wp_head()wp_footer() 函数在这里至关重要。
  3. 代码规范:确保你的代码整洁、有注释,方便自己和他人阅读。
  4. 创建 readme.txt:在主题根目录创建一个 readme.txt 文件,详细说明主题的安装方法、功能特性、作者信息等,这会让你的主题在 WordPress.org 主题目录中更容易被接受。

总结与进阶

恭喜!你已经成功创建了一个功能完整的 WordPress 主题。

进阶学习方向:

  • 子主题: 学习如何创建子主题,这样可以安全地修改父主题,而不会在父主题更新时丢失你的修改。
  • Widgets (小工具): 学习如何创建自定义的小工具区域,让用户可以在后台拖拽添加内容。
  • Theme Options (主题选项): 使用 Settings API 或第三方库(如 Redux Framework)创建一个功能强大的主题设置面板。
  • REST API: 学习如何使用 WordPress 的 REST API 来构建前后端分离的应用。
  • 安全性: 了解 WordPress 的安全最佳实践,如数据验证、转义输出等。

制作主题是一个不断学习和实践的过程,从模仿开始,逐步加入自己的创意和功能,你也能成为一个出色的 WordPress 主题开发者!

分享:
扫描分享到社交APP
上一篇
下一篇