WordPress主题制作全攻略:从零到一

本教程将带你完成一个名为 MyFirstTheme 的基础主题,这个主题将包含现代WordPress开发的核心要素:HTML5 标签、自定义Logo、自定义菜单、侧边栏、文章循环、评论系统和响应式设计

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

第一部分:准备工作

在开始之前,请确保你已经准备好了以下环境:

  1. 本地服务器环境:推荐使用 Local (by Flywheel), XAMPP, MAMPWAMP,这些工具可以在你的电脑上搭建一个本地的PHP和MySQL环境。
  2. WordPress 已安装:在你的本地服务器上成功安装并运行了WordPress。
  3. 代码编辑器:强烈推荐使用 Visual Studio Code (免费且功能强大),或 Sublime Text、Atom 等。
  4. 浏览器开发者工具:现代浏览器(如 Chrome, Firefox)自带的开发者工具,用于调试和检查代码。

第二部分:创建主题的基本结构

WordPress主题的文件都存放在 wp-content/themes/ 目录下。

  1. 创建主题文件夹: 在 wp-content/themes/ 目录下,创建一个新文件夹,命名为 my-first-theme,这个名字必须是小写不含空格

  2. 创建核心文件: 在 my-first-theme 文件夹中,创建以下两个最基本的文件:

    wordpress主题模板制作教程
    (图片来源网络,侵删)
    • style.css主题的“身份证”,WordPress通过它来识别主题。
    • index.php主题的“主页模板”,当没有其他更具体的模板被调用时,WordPress会使用它来显示内容。
  3. 编写 style.css 文件: 用代码编辑器打开 style.css,并添加以下注释块,这是必须的,WordPress会读取这些信息。

    /*
    Theme Name: My First Theme
    Theme URI: https://example.com/my-first-theme
    Author: Your Name
    Author URI: https://example.com
    Description: A simple and clean theme for learning WordPress development.
    Version: 1.0
    License: GNU General Public License v2 or later
    License URI: http://www.gnu.org/licenses/gpl-2.0.html
    Text Domain: myfirsttheme
    */

    你的WordPress后台 -> 外观 -> 主题中,就能看到这个名为 "My First Theme" 的主题了,虽然它现在只是一个空白。


第三部分:构建主题的骨架

一个标准的WordPress页面结构通常包含:<header>(页头)、<main>区)、<aside>(侧边栏)和 <footer>(页脚)。

我们将使用 index.php 来构建这个基本骨架,并引入WordPress的函数。

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

打开 index.php,输入以下HTML结构:

<?php get_header(); ?>
    <div id="primary" class="content-area">
        <main id="main" class="site-main" role="main">
            <!-- WordPress Loop 将在这里 -->
            <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
                <!-- 这里是单篇文章的内容 -->
            <?php endwhile; else : ?>
                <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
            <?php endif; ?>
        </main><!-- #main -->
    </div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>

代码解释

  • <?php ... ?>:这是PHP代码的标记。
  • get_header();:加载一个名为 header.php 的文件,我们稍后会创建它。
  • get_sidebar();:加载一个名为 sidebar.php 的文件。
  • get_footer();:加载一个名为 footer.php 的文件。
  • The Loop (WordPress 循环):这是WordPress的核心,它遍历所有要显示的文章,并为每一篇文章加载内容。if ( have_posts() ) 检查是否有文章,while ( have_posts() ) 循环显示它们,the_post() 设置当前文章。

第四部分:创建模板文件

我们需要创建被 get_header(), get_sidebar(), get_footer() 引用的文件。

  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">
        <?php wp_head(); ?>
    </head>
    <body <?php body_class(); ?>>
        <?php wp_body_open(); ?>
        <header id="masthead" class="site-header">
            <div class="site-branding">
                <?php
                if ( has_custom_logo() ) :
                    the_custom_logo();
                else :
                    // 如果没有设置自定义Logo,则显示网站标题和描述
                    ?>
                    <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 endif; ?>
            </div><!-- .site-branding -->
            <?php
            // 如果有位置被注册,则显示导航菜单
            if ( has_nav_menu( 'primary' ) ) :
                wp_nav_menu( array(
                    'theme_location' => 'primary',
                    'menu_id'        => 'primary-menu',
                ) );
            endif;
            ?>
        </header><!-- #masthead -->

    关键函数

    • language_attributes():输出语言属性(如 lang="zh-CN")。
    • bloginfo( 'charset' ):输出网站字符集(通常是UTF-8)。
    • wp_head()极其重要! 很多插件和WordPress核心功能会通过这个“钩子”来加载CSS和JavaScript文件。绝不能忘记!
    • body_class():为<body>标签添加与当前页面相关的CSS类(如home, single-post, logged-in等),方便样式定制。
    • wp_body_open():另一个重要的钩子,用于在<body>标签后插入内容。
    • has_custom_logo() / the_custom_logo():检查并显示在“自定义” -> “站点身份”中设置的自定义Logo。
    • bloginfo( 'name' ) / bloginfo( 'description' ):显示网站标题和描述。
    • has_nav_menu() / wp_nav_menu():检查并显示我们即将注册的导航菜单。
  2. 创建 footer.php: 这个文件包含网站的页脚部分。

        <footer id="colophon" class="site-footer">
            <div class="site-info">
                <a href="<?php echo esc_url( __( 'https://wordpress.org/', 'myfirsttheme' ) ); ?>">
                    <?php
                    /* translators: %s: CMS name, i.e. WordPress. */
                    printf( esc_html__( 'Proudly powered by %s', 'myfirsttheme' ), 'WordPress' );
                    ?>
                </a>
                <span class="sep"> | </span>
                <?php printf( /* translators: 1: Theme name, 2: Theme author */ esc_html__( '%1$s by %2$s.', 'myfirsttheme' ), 'My First Theme', 'Your Name' ); ?>
            </div><!-- .site-info -->
        </footer><!-- #colophon -->
    <?php wp_footer(); ?>
    </body>
    </html>

    关键函数

    • wp_footer()wp_head() 同样重要! 很多插件(如联系表单、聊天窗口)会通过这个钩子在页脚加载它们的脚本。绝不能忘记!
  3. 创建 sidebar.php: 这个文件包含侧边栏。

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

第五部分:完善文章循环和样式

现在我们的骨架有了,但文章循环里是空的,而且没有任何样式。

  1. index.php 中填充文章循环: 修改 index.php 中 Loop 的部分。

    <main id="main" class="site-main" role="main">
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <header class="entry-header">
                    <?php the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' ); ?>
                </header><!-- .entry-header -->
                <?php if ( has_post_thumbnail() ) : ?>
                    <div class="post-thumbnail">
                        <a href="<?php the_permalink(); ?>">
                            <?php the_post_thumbnail( 'large' ); ?>
                        </a>
                    </div>
                <?php endif; ?>
                <div class="entry-content">
                    <?php the_excerpt(); // 显示文章摘要 ?>
                </div><!-- .entry-content -->
                <footer class="entry-footer">
                    <?php
                    _e( 'Posted in: ', 'myfirsttheme' );
                    the_category( ', ' ); // 显示文章分类
                    ?>
                </footer><!-- .entry-footer -->
            </article><!-- #post-<?php the_ID(); ?> -->
        <?php endwhile; ?>
            <div class="navigation">
                <div class="nav-previous"><?php next_posts_link( '&larr; Older posts' ); ?></div>
                <div class="nav-next"><?php previous_posts_link( 'Newer posts &rarr;' ); ?></div>
            </div>
        <?php else : ?>
            <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
        <?php endif; ?>
    </main><!-- #main -->

    新函数解释

    • the_ID():输出当前文章的ID。
    • post_class():为文章容器添加CSS类(如post, hentry, sticky等)。
    • the_title() / get_permalink():输出文章标题和链接。
    • has_post_thumbnail() / the_post_thumbnail():检查并显示文章特色图片。
    • the_excerpt():显示文章的摘要。
    • the_category():显示文章所属的分类。
    • next_posts_link() / previous_posts_link():生成分页链接。
  2. 添加基本CSS样式: 打开 style.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;
    }
    .container {
        max-width: 1100px;
        margin: 0 auto;
        padding: 0 2rem;
    }
    /* Header 样式 */
    .site-header {
        background: #333;
        color: #fff;
        padding: 1rem 0;
    }
    .site-branding a {
        color: #fff;
        text-decoration: none;
    }
    .site-title a {
        font-size: 2rem;
    }
    /* 导航菜单样式 */
    #primary-menu {
        list-style: none;
        padding: 0;
        margin: 0;
        display: flex;
    }
    #primary-menu li {
        margin-left: 1.5rem;
    }
    #primary-menu a {
        color: #fff;
        text-decoration: none;
    }
    /* 主内容区和侧边栏布局 */
    #primary, #secondary {
        padding: 2rem 0;
    }
    .content-area {
        float: left;
        width: 70%;
    }
    .widget-area {
        float: right;
        width: 25%;
    }
    /* 文章样式 */
    .article {
        background: #fff;
        margin-bottom: 2rem;
        padding: 2rem;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    .entry-title a {
        color: #333;
        text-decoration: none;
    }
    .post-thumbnail img {
        width: 100%;
        height: auto;
    }
    /* 页脚样式 */
    .site-footer {
        background: #333;
        color: #fff;
        text-align: center;
        padding: 1.5rem 0;
        margin-top: 2rem;
    }

    注意:为了让WordPress加载这个CSS文件,你必须在 header.php<head> 标签内添加 wp_enqueue_style 函数,这是一种更专业、更推荐的做法。

    修改 header.php<head> 部分:

    <head>
        <meta charset="<?php bloginfo( 'charset' ); ?>">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php wp_head(); ?>
        <?php wp_enqueue_style( 'my-first-theme-style', get_stylesheet_uri() ); ?>
    </head>
    • get_stylesheet_uri():自动获取当前主题目录下的 style.css 文件的路径。

第六部分:添加自定义功能(函数文件)

WordPress主题通过一个名为 functions.php 的文件来添加自定义功能,这个文件位于主题根目录下,它像一个“插件”,可以在主题激活时执行代码。

  1. 创建 functions.php: 在 my-first-theme 文件夹中创建 functions.php 文件。

  2. 添加功能: 在 functions.php 中添加以下代码:

    <?php
    /**
     * 主题设置
     */
    function myfirsttheme_setup() {
        // 支持自定义Logo
        add_theme_support( 'custom-logo', array(
            'height'      => 100,
            'width'       => 300,
            'flex-height' => true,
            'flex-width'  => true,
            'header-text' => array( 'site-title', 'site-description' ),
        ) );
        // 支持导航菜单
        register_nav_menus( array(
            'primary' => '主导航菜单',
        ) );
        // 添加文章格式支持(可选)
        add_theme_support( 'post-formats', array( 'aside', 'image', 'video' ) );
        // 添加特色图片支持
        add_theme_support( 'post-thumbnails' );
        // 让WordPress管理标题标签
        add_theme_support( 'title-tag' );
        // 添加HTML5标签支持
        add_theme_support( 'html5', array( 'comment-list', 'comment-form', 'search-form', 'gallery', 'caption' ) );
    }
    add_action( 'after_setup_theme', 'myfirsttheme_setup' );
    /**
     * 注册侧边栏
     */
    function myfirsttheme_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', 'myfirsttheme_widgets_init' );
    /**
     * 注册和加载CSS/JS
     */
    function myfirsttheme_scripts() {
        // 加载main.js文件 (如果需要)
        // wp_enqueue_script( 'myfirsttheme-main-script', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true );
    }
    add_action( 'wp_enqueue_scripts', 'myfirsttheme_scripts' );

    代码解释

    • myfirsttheme_setup():通过 add_theme_support() 来启用WordPress的内置功能,如Logo、菜单、特色图片等。add_action( 'after_setup_theme', ... ) 表示在主题基本设置完成后执行这个函数。
    • myfirsttheme_widgets_init():使用 register_sidebar() 来注册一个侧边栏区域,这样你就可以在WordPress后台 -> 外观 -> 小工具中向它添加内容了。
    • myfirsttheme_scripts():这是加载CSS和JavaScript文件的标准位置,我们已经在 header.php 中用 wp_enqueue_style 加载了CSS,这里可以用来加载JS文件。

第七部分:激活主题并测试

  1. 激活主题: 登录你的WordPress本地后台,进入 外观 -> 主题,找到 "My First Theme",点击 “激活” 按钮。

  2. 配置主题

    • 设置Logo:进入 外观 -> 自定义 -> 站点身份,上传你的Logo。
    • 设置菜单:进入 外观 -> 菜单,创建一个新菜单,然后将其分配给“主导航菜单”这个位置。
    • 添加小工具:进入 外观 -> 小工具,将一些小工具(如“文章归档”、“分类目录”)拖拽到“主侧边栏”中。
  3. 创建文章: 创建几篇测试文章,并确保至少有一篇设置了特色图片

刷新你的网站首页,你应该能看到一个基本成型、有Logo、有导航、有文章列表、有侧边栏的WordPress网站了!


进阶方向

你已经成功创建了一个基础主题!接下来可以探索:

  • 响应式设计:使用CSS媒体查询(@media)让你的主题在手机和平板上也能完美显示。
  • 创建更多模板
    • single.php:用于显示单篇文章。
    • page.php:用于显示“页面”(Page)。
    • archive.php:用于显示分类、标签、日期等归档页面。
    • search.phpsearchform.php:用于搜索功能。
    • php:用于“页面未找到”的错误页面。
  • 使用模板标签:深入学习更多WordPress模板标签,如 get_template_part()(用于复用代码块)、the_author()(显示作者)等。
  • 集成自定义izer(自定义器):通过 functions.php 添加更多自定义选项,让用户可以在“外观 -> 自定义”中轻松修改主题颜色、布局等。

这份教程为你打下了坚实的基础,最好的学习方式就是动手实践,不断尝试和修改,祝你制作愉快!