WordPress主題開發入門指南:從零開始構建你嘅第一個自訂主題

4分鐘閱讀
2026-03-12
2026-06-03
2,220
當你透過以下連結購物,我會獲得佣金,對你嚟講冇額外成本。.

準備工作同環境搭建

喺開始寫程式碼之前,你需要一個合適嘅開發環境。呢個通常意味住要喺你部本地電腦度搭建一個可以運行 WordPress 嘅伺服器環境。你可以揀用一啲集成軟件包,例如 XAMPP、MAMP(適用於 Mac)或者 Local by Flywheel,佢哋可以一鍵安裝 Apache、MySQL 同 PHP。裝好本地伺服器之後,去 WordPress.org 下載最新嘅 WordPress 程式並完成安裝。

跟住,你需要搵到 WordPress 嘅主題目錄。佢位於 wp-content/themes/。喺呢個目錄下面,為你嘅新主題創建一個文件夾,例如 my-first-theme。呢個文件夾嘅名就係你嘅主題標識符,建議用細楷字母、數字同連字號,避免用空格。

一個 WordPress 主題最基礎嘅檔案只有兩個:style.css 同埋 index.phpstyle.css 唔單止係一個樣式表,更加係一個主題嘅「身份證」,佢透過檔案頂部嘅註解區塊向 WordPress 聲明主題資訊。

推薦閱讀 WordPress 主題開發入門:從零開始打造自訂主題

建立主題資訊檔案

style.css 檔案嘅開頭必須包含一個特定嘅樣式表頂部資訊。呢個係 WordPress 識別同載入主題嘅關鍵。下面係一個最基本嘅示例:

UltaHost WordPress 主機
30日退款保證,無限頻寬同數據庫,免費DDoS防護,買3年優惠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
License: GNU General Public License v2 or later
Text Domain: my-first-theme
*/

其中,Text Domain 用於主題國際化(翻譯),通常同主題資料夾名稱保持一致。Theme Name 會喺 WordPress 後台嘅「外觀」->「主題」列表度顯示。

創建核心模板文件

index.php 係你個主題最核心嘅模板檔案。當 WordPress 搵唔到更具體嘅模板檔案(例如 single.phppage.php)嗰陣,就會用佢做預設嘅後備模板。一個最簡單嘅 index.php 可以淨係包含獲取網站頭部、主循環同網站腳部嘅函數。

<?php get_header(); ?>

<main>
    &lt;?php
    if ( have_posts() ) :
        while ( have_posts() ) : the_post();
            // 文章内容输出
            the_title( &#039;<h2>', '</h2>' );
            the_content();
        endwhile;
    else :
        echo '<p>没有找到任何文章。</p>';
    endif;
    ?&gt;
</main>

而家,你嘅主題已經可以俾 WordPress 辨認到同啟動到啦。雖然功能簡單,但呢個係建立一切嘅基礎。

理解模板層級同核心檔案

WordPress 用一套叫做「模板層級」嘅智能系統,嚟決定為當前請求嘅頁面用邊個模板檔案。理解呢個層級係高效開發嘅關鍵。佢嘅核心原則係:越具體嘅模板,優先級越高。

推薦閱讀 WordPress主題開發入門指南:從零開始搭建你嘅第一個主題

文章同頁面範本

對於單篇博客文章,WordPress 會跟以下順序搵模板:single-post-{slug}.php -> single-post-{id}.php -> single-post.php -> single.php -> singular.php -> index.php。例如,一篇別名係「hello-world」嘅文章,會優先使用 single-post-hello-world.php

對於獨立頁面(Page),順序係:custom template(頁面屬性中指定) -> page-{slug}.php -> page-{id}.php -> page.php -> singular.php -> index.php

歸檔與首頁模板

博客文章列表頁(歸檔頁)都有其規則。主博客首頁:home.php -> index.php。分類歸檔頁:category-{slug}.php -> category-{id}.php -> category.php -> archive.php -> index.php。標籤、作者、日期歸檔等跟返類似模式。

hosting.com 共享主機
高效能,配備 AMD EPYC 處理器、NVMe SSD 儲存同 LiteSpeed,提供全天候專業內部支援,採用先進安全措施,包括 SSL、暴力破解、惡意軟件同 DDoS 防護,可節省高達 73%。

搜尋頁面用 search.php,404錯誤頁面用 404.php。如果呢啲特定檔案唔存在,最終都會退返去 index.php

創建常用模板檔案

基於以上層級,你應該創建幾個最常用嘅模板檔案嚟增強主題功能。首先係 header.php,佢包含 HTML 文檔嘅 <head> 部分同網站嘅頁頭區域。

<!DOCTYPE html>
<html no numeric noise key 1008>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
</head>
<body no numeric noise key 1005>
<?php wp_body_open(); ?>
<header>
    <h1><a href="/yue/</?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></h1>
    <p><?php bloginfo( 'description' ); ?></p>
    <nav>
        'primary',
            'container'      =&gt; false,
        ) );
        ?&gt;
    </nav>
</header>

footer.php 包含頁尾內容同腳本調用。

推薦閱讀 掌握 WordPress 主題開發核心:從零構建自訂主題嘅最佳實踐指南

<footer>
    <p>©</p>
</footer>
<?php wp_footer(); ?>
</body>
</html>

functions.php 係主題嘅「大腦」,用嚟加功能、註冊菜單、樣式表同腳本。

主題功能同樣式整合

functions.php 呢個檔案唔係必須嘅,但冇咗佢,主題嘅功能會好有限。呢個檔案喺主題初始化時自動加載,係掛載功能、過濾器同掛鈎嘅最佳地方。

InterServer 共享主機
共享主機:每月1TB,只需£2.50;首月只需£0.10,使用優惠碼 tryinterserver。461個雲端應用程式腳本,一鍵安裝。

註冊導航選單同側邊欄

functions.php 入面,用 register_nav_menus() 用函數嚟聲明主題支援嘅菜單位置。

function my_first_theme_setup() {
    // 注册一个主导航菜单
    register_nav_menus( array(
        'primary' => __( '主导航菜单', 'my-first-theme' ),
    ) );
    // 为文章和评论添加 RSS feed 链接支持
    add_theme_support( 'automatic-feed-links' );
    // 支持文章特色图像
    add_theme_support( 'post-thumbnails' );
    // 支持 HTML5 标记
    add_theme_support( 'html5', array( 'comment-list', 'comment-form', 'search-form', 'gallery', 'caption', 'style', 'script' ) );
    // 支持自定义 logo
    add_theme_support( 'custom-logo' );
}
add_action( 'after_setup_theme', 'my_first_theme_setup' );

使用 register_sidebar() 函數嚟註冊小工具區域(側邊欄)。

function my_first_theme_widgets_init() {
    register_sidebar( array(
        'name'          =&gt; __( '主侧边栏', 'my-first-theme' ),
        'id'            =&gt; 'sidebar-1',
        'description'   =&gt; __( '在此添加小工具。', 'my-first-theme' ),
        'before_widget' =&gt; '<section id="%1$s" class="widget %2$s">',
 'after_widget'  =&gt; '</section>',
 'before_title'  =&gt; '<h2 class="widget-title">',
 'after_title'   =&gt; '</h2>',
    ) );
}
add_action( 'widgets_init', 'my_first_theme_widgets_init' );

動態引入樣式同腳本

正確嘅做法係使用 wp_enqueue_style() 同埋 wp_enqueue_script() 函數嚟將 CSS 同 JavaScript 檔案加入隊列。咁樣確保咗依賴關係被正確處理,同埋唔會重複載入。

function my_first_theme_scripts() {
    // 引入主题的主样式表
    wp_enqueue_style( 'my-first-theme-style', get_stylesheet_uri(), array(), wp_get_theme()->get( 'Version' ) );

// 引入一个自定义的 CSS 文件
    wp_enqueue_style( 'my-first-theme-custom', get_template_directory_uri() . '/assets/css/custom.css', array( 'my-first-theme-style' ), '1.0' );

// 引入一个 JavaScript 文件
    wp_enqueue_script( 'my-first-theme-navigation', get_template_directory_uri() . '/assets/js/navigation.js', array(), '1.0', true );

// 为评论回复功能添加脚本(仅在需要时加载)
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'my_first_theme_scripts' );

完善模板同進階概念

隨住主題核心功能嘅建立,你可以開始細化各個模板檔案,實現更專業嘅佈局同功能。

構建文章列表循環

archive.phphome.php 當中,你通常需要以摘要形式展示多篇文章。可以利用 WordPress 提供嘅模板函數,例如 the_excerpt()the_post_thumbnail()

<?php if ( have_posts() ) : ?>
    <div class="posts-list">
        <?php while ( have_posts() ) : the_post(); ?>
            <article id="post-<?php the_ID(); ?>" no numeric noise key 1015>
                <?php if ( has_post_thumbnail() ) : ?>
                    <a href="/yue/</?php the_permalink(); ?>">
                        <?php the_post_thumbnail( 'medium' ); ?>
                    </a>
                <?php endif; ?>
                <h2><a href="/yue/</?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                <div class="entry-meta">
                    |
                </div>
                <div class="entry-summary">
                    <?php the_excerpt(); ?>
                </div>
                <a href="/yue/</?php the_permalink(); ?>" class="read-more">睇多啲</a>
            </article>
        <?php endwhile; ?>
    </div>
    
    <p><?php _e( '抱歉,没有找到符合条件的内容。', 'my-first-theme' ); ?></p>
<?php endif; ?>

實現評論模板

評論功能係博客嘅重要組成部分。WordPress 提供咗強大嘅評論模板函數 comments_template()。最佳做法係將評論嘅顯示同表單放喺一個獨立嘅檔案度,通常係 comments.php,然後喺 single.php 入面調用佢。

single.php 嘅文章內容輸出之後,加返:

<?php
if ( comments_open() || get_comments_number() ) :
    comments_template();
endif;
?>

跟住就整 comments.php 檔案嚟處理評論列表同表單嘅渲染。你可以從現成嘅主題(例如 Twenty Twenty-One)度複製一個基礎嘅 comments.php 並進行修改,呢個係一個複雜但標準化嘅部分。

加入主題自訂選項

為咗令用戶唔使修改代碼就可以調整主題,你可以利用 WordPress 定制器(Customizer)API。透過 WP_Customize_Manager 對象,你可以加入設定、控件同區域。

function my_first_theme_customize_register( $wp_customize ) {
    // 添加一个‘颜色’板块
    $wp_customize->add_section( 'theme_colors', array(
        'title'    => __( '主题颜色', 'my-first-theme' ),
        'priority' => 30,
    ) );

// 添加一个‘主色调’设置
    $wp_customize->add_setting( 'primary_color', array(
        'default'           => '#0073aa',
        'sanitize_callback' => 'sanitize_hex_color',
        'transport'         => 'postMessage', // 实时预览
    ) );

// 为该设置添加一个颜色选择器控件
    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'primary_color', array(
        'label'    => __( '主色调', 'my-first-theme' ),
        'section'  => 'theme_colors',
        'settings' => 'primary_color',
    ) ) );
}
add_action( 'customize_register', 'my_first_theme_customize_register' );

之後,你喺 style.css 或者透過內聯樣式動態輸出呢個顏色值。

摘要

WordPress 主題開發係一個由結構到樣式、由基礎到細節嘅漸進過程。由最基礎 style.css 同埋 index.php 開始,你建立咗主題嘅基石。理解模板層級令你能够創建針對唔同頁面類型嘅精準模板。functions.php 就係你擴展主題功能嘅強大工具,用嚟整合導航、小工具、樣式腳本同埋自訂器選項。最後,透過完善文章循環、評論模板同埋自訂選項,你嘅主題就會變得又專業又用户友善。記住,不斷參考官方手冊同埋現有優質主題嘅程式碼,係提升開發技能嘅最佳途徑。

常見問題

一個 WordPress 主題最少需要邊啲檔案?

理論上,一個 WordPress 主題只需要兩個檔案:style.css 同埋 index.phpstyle.css 必須包含正確嘅主題信息頭部註解,等 WordPress 可以識別到。而 index.php 作為所有頁面嘅預設後備模板。當然,咁樣嘅主題功能好有限,但係可以激活同運行到。

點樣可以令我嘅主題支援多語言(國際化)?

你需要用 WordPress 嘅國際化(i18n)功能。喺 functions.php 入面,用 load_theme_textdomain() 函數嚟載入翻譯檔案。喺你嘅主題代碼入面,將所有面向用戶嘅字串用 __()(用於回顯)或者 _e()(用於直接輸出)等翻譯函數包住,並指定你喺 style.css 入面定義 Text Domain。然後,可以用好似 Poedit 咁嘅工具生成 .pot 模板檔案,俾翻譯人員創建 .po 同 .mo 翻譯檔案。

點解我嘅自訂樣式或者腳本冇加載到?

最常見嘅原因係你喺 functions.php 入面排隊加載樣式或者腳本嘅掛鈎函數冇正確連接到 WordPress 嘅動作上。確保你已經將包含 wp_enqueue_style()wp_enqueue_script() 嘅函數,通過 add_action( ‘wp_enqueue_scripts’, ‘your_function_name’ ) 掛載到 wp_enqueue_scripts 呢個動作上。同時,檢查文件路徑(get_template_directory_uri())係咪正確,同埋文件係咪真係喺呢個路徑下面。

點樣為特定頁面創建獨特嘅模板?

主要有兩種方法。第一種係使用頁面模板:喺 PHP 檔案頂部加一個特定嘅註解塊,例如 /* Template Name: 全宽页面 */,然後將佢保存喺你嘅主題目錄下。喺 WordPress 後台編輯頁面嗰陣,就可以喺「頁面屬性」->「範本」下拉框度揀佢。第二種係利用範本層級:例如,要為別名係「contact」嘅頁面創建範本,只需要創建一個名為 page-contact.php 嘅檔案,WordPress 會自動優先使用佢嚟渲染呢個頁面。前者嘅優勢係可以喺後台自由分配,後者嘅優勢係命名規則自動生效。