Skip to content

主题开发基础

主题开发概述

什么是 WordPress 主题?

主题是一组控制网站外观的模板文件。每个主题都可以有不同的布局、设计和功能,但都使用 WordPress 核心功能。

主题 vs 插件

方面主题插件
主要作用控制外观扩展功能
切换影响外观完全改变功能保持
激活方式同时只能激活一个可以同时激活多个
生命周期与网站共存可随时停用

主题目录结构

my-theme/
├── style.css              # 必须:主题样式表(含头部信息)
├── index.php              # 必须:回退模板文件
├── functions.php          # 可选:主题函数
├── header.php             # 页头模板
├── footer.php             # 页脚模板
├── sidebar.php            # 侧边栏模板
├── single.php              # 单篇文章模板
├── page.php                # 单页模板
├── front-page.php          # 首页模板
├── archive.php             # 存档页模板
├── search.php              # 搜索结果模板
├── 404.php                 # 404 错误模板
├── comments.php            # 评论模板
├── screenshot.png          # 主题预览图(880×660px)
├── assets/                 # 静态资源
│   ├── css/
│   ├── js/
│   └── images/
└── template-parts/          # 模板部件
    ├── content.php
    └── content-none.php

创建第一个主题

步骤 1:创建主题目录

bash
wp-content/themes/my-first-theme/

步骤 2:创建 style.css

css
/*
Theme Name: 我的第一个主题
Theme URI: https://example.com/my-first-theme
Author: 开发者名称
Author URI: https://example.com
Description: 一个简洁的个人博客主题
Version: 1.0.0
Requires at least: 6.0
Tested up to: 6.4
Requires PHP: 7.4
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: my-first-theme
Tags: blog, custom-colors, custom-logo, featured-images, threaded-comments
*/

/* ===== 基础样式 ===== */
:root {
    --primary-color: #21759b;
    --text-color: #333;
    --bg-color: #fff;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    color: var(--text-color);
    background: var(--bg-color);
    line-height: 1.6;
}

/* ===== 容器 ===== */
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}

/* ===== 导航 ===== */
.site-header {
    padding: 20px 0;
    border-bottom: 1px solid #eee;
}

.main-nav ul {
    display: flex;
    list-style: none;
    gap: 20px;
}

.main-nav a {
    text-decoration: none;
    color: var(--text-color);
}

步骤 3:创建 functions.php

php
<?php
/**
 * 主题功能设置
 */

// 定义主题常量
define('MY_THEME_VERSION', '1.0.0');

// 主题支持
function my_theme_setup() {
    // 支持文章缩略图
    add_theme_support('post-thumbnails');
    
    // 支持标题标签
    add_theme_support('title-tag');
    
    // 支持自定义 Logo
    add_theme_support('custom-logo', array(
        'height' => 100,
        'width' => 300,
        'flex-height' => true,
        'flex-width'  => true,
    ));
    
    // 支持导航菜单
    register_nav_menus(array(
        'primary'   => '主导航',
        'footer'    => '页脚导航',
    ));
    
    // 支持编辑器样式
    add_theme_support('editor-styles');
    
    // 支持响应式嵌入
    add_theme_support('responsive-embeds');
}
add_action('after_setup_theme', 'my_theme_setup');

// 加载样式和脚本
function my_theme_scripts() {
    // 主样式表
    wp_enqueue_style(
        'my-theme-style',
        get_stylesheet_uri(),
        array(),
        MY_THEME_VERSION
    );
    
    // 响应式样式
    wp_enqueue_style(
        'my-theme-responsive',
        get_template_directory_uri() . '/assets/css/responsive.css',
        array(),
        MY_THEME_VERSION
    );
    
    // 主脚本
    wp_enqueue_script(
        'my-theme-main',
        get_template_directory_uri() . '/assets/js/main.js',
        array(),
        MY_THEME_VERSION,
        true
    );
}
add_action('wp_enqueue_scripts', 'my_theme_scripts');

// 添加自定义图像尺寸
function my_theme_image_sizes() {
    add_image_size('featured-image', 800, 600, true);
    add_image_size('thumbnail-medium', 300, 200, true);
}
add_action('after_setup_theme', 'my_theme_image_sizes');

// 注册侧边栏
function my_theme_widgets() {
    register_sidebar(array(
        'name'          => '主侧边栏',
        'id'            => 'main-sidebar',
        'description'   => '主侧边栏区域',
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ));
}
add_action('widgets_init', 'my_theme_widgets');

步骤 4:创建模板文件

header.php

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(); ?>

<div id="page" class="site">
    <header id="masthead" class="site-header">
        <div class="container">
            <?php if (has_custom_logo()): ?>
                <?php the_custom_logo(); ?>
            <?php else: ?>
                <h1 class="site-title">
                    <a href="<?php echo esc_url(home_url('/')); ?>">
                        <?php bloginfo('name'); ?>
                    </a>
                </h1>
            <?php endif; ?>
            
            <nav class="main-nav">
                <?php
                wp_nav_menu(array(
                    'theme_location' => 'primary',
                    'container'      => false,
                    'menu_class'     => 'nav-menu',
                ));
                ?>
            </nav>
        </div>
    </header>
    
    <main id="main" class="site-main">
php
    </main><!-- #main -->
    
    <footer id="colophon" class="site-footer">
        <div class="container">
            <div class="footer-content">
                <p>&copy; <?php echo date('Y'); ?> 
                    <a href="<?php echo esc_url(home_url('/')); ?>">
                        <?php bloginfo('name'); ?>
                    </a>
                </p>
                
                <?php if (has_nav_menu('footer')): ?>
                    <nav class="footer-nav">
                        <?php wp_nav_menu(array('theme_location' => 'footer')); ?>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
    </footer>
</div><!-- #page -->

<?php wp_footer(); ?>
</body>
</html>

index.php

php
<?php get_header(); ?>

<div class="container">
    <?php if (have_posts()): ?>
        
        <?php if (is_home() && !is_front_page()): ?>
            <h1 class="page-title"><?php single_post_title(); ?></h1>
        <?php endif; ?>
        
        <div class="posts-list">
            <?php while (have_posts()): the_post(); ?>
                <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                    <header class="entry-header">
                        <?php if (has_post_thumbnail()): ?>
                            <div class="post-thumbnail">
                                <a href="<?php the_permalink(); ?>">
                                    <?php the_post_thumbnail('medium'); ?>
                                </a>
                            </div>
                        <?php endif; ?>
                        
                        <h2 class="entry-title">
                            <a href="<?php the_permalink(); ?>">
                                <?php the_title(); ?>
                            </a>
                        </h2>
                        
                        <div class="entry-meta">
                            <span class="posted-on">
                                <time><?php echo get_the_date(); ?></time>
                            </span>
                            <span class="byline">
                                作者: <?php the_author(); ?>
                            </span>
                        </div>
                    </header>
                    
                    <div class="entry-summary">
                        <?php the_excerpt(); ?>
                    </div>
                    
                    <footer class="entry-footer">
                        <a href="<?php the_permalink(); ?>" class="read-more">
                            阅读全文
                        </a>
                    </footer>
                </article>
            <?php endwhile; ?>
            
            <!-- 分页 -->
            <div class="pagination">
                <?php the_posts_pagination(); ?>
            </div>
            
        <?php else: ?>
            
            <div class="no-results">
                <h2>未找到内容</h2>
                <p>抱歉,没有找到您要查找的内容。</p>
                <?php get_search_form(); ?>
            </div>
            
        <?php endif; ?>
</div>

<?php get_footer(); ?>

常用主题函数

条件标签

php
<?php
// 页面判断
is_home()           // 首页
is_front_page()     // 前台页面
is_single()         // 单篇文章
is_page()           // 页面
is_archive()        // 存档页
is_category()       // 分类存档
is_tag()            // 标签存档
is_search()         // 搜索结果
is_404()            // 404 页面
is_singular()       // 任何单页类型

// 作者判断
is_author('john')   // 指定作者
is_author(1)        // 作者 ID

// 日期判断
is_date()           // 任何日期存档
is_year()           // 年存档
is_month()          // 月存档
is_day()            // 日存档
?>

模板标签

php
<?php
// 标题和链接
the_title()                    // 文章标题
the_permalink()                // 文章链接
the_content()                  // 文章内容
the_excerpt()                   // 文章摘要

// 元信息
the_date()                      // 发布日期
the_time()                      // 发布时间
the_author()                    // 作者名称
get_the_author_meta('email')    // 作者信息

// 分类和标签
the_category()                  // 分类
the_tags()                      // 标签
get_the_ID()                    // 文章 ID

// 图片
has_post_thumbnail()            // 是否有缩略图
the_post_thumbnail()            // 缩略图
get_post_thumbnail_id()         // 缩略图 ID

// 其他
the_ID()                        // 当前对象 ID
post_class()                    // 文章 CSS 类
?>

主题定制器

添加自定义设置

php
// functions.php
function my_theme_customize_register($wp_customize) {
    // 添加面板
    $wp_customize->add_panel('my_theme_panel', array(
        'title' => '主题设置',
        'priority' => 130,
    ));
    
    // 添加版块
    $wp_customize->add_section('colors_section', array(
        'title' => '颜色设置',
        'panel' => 'my_theme_panel',
    ));
    
    // 添加设置
    $wp_customize->add_setting('primary_color', array(
        'default' => '#21759b',
        'sanitize_callback' => 'sanitize_hex_color',
    ));
    
    // 添加控件
    $wp_customize->add_control(
        new WP_Customize_Color_Control(
            $wp_customize,
            'primary_color',
            array(
                'label' => '主色调',
                'section' => 'colors_section',
                'settings' => 'primary_color',
            )
        )
    );
}
add_action('customize_register', 'my_theme_customize_register');

输出定制值

php
// 在模板中使用
$primary_color = get_theme_mod('primary_color', '#21759b');
echo '<style>:root { --primary: ' . esc_attr($primary_color) . '; }</style>';

下一步

基于 WordPress官方文档 构建