入门级WordPress主题开发:从零开始构建你的首个定制主题

5 分鐘閱讀
2026-03-20
2026-06-03
2,099
通过下方链接进行购物时,您无需支付额外费用,我就能获得佣金。.

准备工作与环境搭建

在開始編寫程式碼之前,你需要一個合適的開發環境。這包括一個本地的伺服器環境(如XAMPP、MAMP或Local by Flywheel)以及一個程式碼編輯器(如VS Code、PhpStorm或Sublime Text)。確保你的本地環境支援PHP(版本7.4或更高)和MySQL/MariaDB。

接下來,你需要在WordPress安裝目錄的wp-content/themes資料夾下建立一個新的資料夾,這將成為你的主題目錄。例如,你可以建立一個名為my-first-theme的資料夾。這是你所有主題檔案的“家”。

一個WordPress主題最基礎的檔案只有兩個:style.css以及index.php其中,style.css不僅是樣式表,更是主題的“身份證”,它透過檔案頭部的註釋資訊向WordPress宣告主題的名稱、作者、描述等元資料。

推荐阅读 深入解析WordPress主題開發:從入門到精通的核心技術指南

建立主題資訊檔案

在你的主題資料夾中,建立style.css檔案,並輸入以下基礎資訊:

UltaHost WordPress 主機
30天退款保證,無限頻寬與資料庫,免費的 DDoS 防護,購買3年優惠50%
/*
Theme Name: 我的第一个主题
Theme URI: https://example.com/my-first-theme/
Author: 你的名字
Author URI: https://example.com/
Description: 这是一个用于学习WordPress主题开发的入门级主题。
Version: 1.0
License: GNU General Public License v2 or later
Text Domain: my-first-theme
*/

這段註釋是必需的。WordPress正是透過讀取Theme Name這一行來在後臺的主題列表中識別並顯示你的主題。其他資訊如Text Domain是為國際化(翻譯)做準備。

创建核心模板文件

接下來,建立最基本的index.php檔案。即使這個檔案暫時為空,只要style.css資訊完整,你的主題就會出現在WordPress後臺的“外觀”->“主題”列表中,並可以被啟用。現在,讓我們在index.php中寫入一個最簡單的HTML結構來輸出部落格標題和文章內容。

<!DOCTYPE html>
<html no numeric noise key 1014>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
</head>
<body no numeric noise key 1011>
    <header>
        <h1><a href="/zh-tw/</?php echo esc_url( home_url( '/' ) ); ?>"></a></h1>
        <p></p>
    </header>
    <main>
        
                <article>
                    <h2><a href="/zh-tw/</?php the_permalink(); ?>"></a></h2>
                    <div></div>
                </article>
                <?php
            endwhile;
        else :
            echo '<p>暂无文章。</p>';
        endif;
        ?>
    </main>
    <footer>
        <p>©</p>
    </footer>
    
</body>
</html>

這段程式碼使用了多個WordPress核心的模板标签,例如bloginfo()the_title()the_content()函数wp_head()以及wp_foot()是關鍵的鉤子,允許WordPress核心、外掛和其他指令碼在頁面的頭部和尾部插入必要程式碼。

理解模板層級與建立核心模板

WordPress使用一套稱為模板层级的規則來決定對於特定的頁面請求,應該使用哪個模板檔案來渲染。這是主題開發中最核心的概念之一。簡單來說,WordPress會從最具體的模板檔案開始尋找,如果不存在,則回退到更通用的檔案,最終回退到index.php

推荐阅读 WordPress主题开发入门指南:从零开始搭建你的第一个定制主题

為文章詳情頁建立模板

當用戶訪問單篇文章時,WordPress會優先尋找single-post.php若不存在,则使用single.php最后才是index.php。讓我們建立一個single.php來專門控制單篇文章的顯示。

<main id="primary" class="site-main">
    
        <article id="post-<?php the_ID(); ?>" no numeric noise key 1009>
            <header class="entry-header">
                &lt;?php the_title( &#039;<h1 class="entry-title">', '</h1>' ); ?&gt;
                <div class="entry-meta">
                    发布于:<?php the_date(); ?> | 作者:<?php the_author(); ?>
                </div>
            </header>
            <div class="entry-content">
                
            </div>
            <footer class="entry-footer">
                分类:<?php the_category( ', ' ); ?>
                <?php the_tags( '标签:', ', ' ); ?>
            </footer>
        </article>
        <?php
        // 上一篇/下一篇导航
        the_post_navigation();
        // 评论模板
        if ( comments_open() || get_comments_number() ) :
            comments_template();
        endif;
    endwhile;
    ?>
</main>

這個模板引入了三個重要的模板部件:get_header()get_sidebar()以及get_footer()它们分别用于引入header.phpsidebar.php以及footer.php檔案,這是實現程式碼複用和模組化設計的關鍵。

建立頁面模板

對於靜態頁面(如“關於我們”),WordPress會尋找page.php。建立page.php,其結構與single.php類似,但通常不顯示分類、標籤和釋出時間等元資訊。

hostng.com 共享主机
高效能,配备 AMD EPYC CPU、NVMe SSD 存储和 LiteSpeed,全天候 24 小时专业内部支持,先进的安全措施包括 SSL、暴力破解、恶意软件和 DDoS 防护,节省高达 731 TB/月的带宽成本。
<main id="primary" class="site-main">
    
        <article id="post-<?php the_ID(); ?>" no numeric noise key 1005>
            <header class="entry-header">
                &lt;?php the_title( &#039;<h1 class="entry-title">', '</h1>' ); ?&gt;
            </header>
            <div class="entry-content">
                
            </div>
        </article>
        
</main>

實現主題功能與樣式

一個完整的主題不僅需要模板檔案,還需要透過functions.php檔案來新增功能、註冊選單、小工具區域,並透過style.css新增樣式。

主題功能函式檔案

在你的主題根目錄下建立functions.php。這個檔案在主題初始化時自動載入,用於存放所有自定義PHP函式和掛鉤。

<?php
/**
 * 我的第一个主题的功能函数
 */

// 添加主题支持功能
function my_first_theme_setup() {
    // 让WordPress管理文档标题
    add_theme_support( 'title-tag' );
    // 启用文章和页面的特色图像(缩略图)功能
    add_theme_support( 'post-thumbnails' );
    // 注册导航菜单
    register_nav_menus(
        array(
            'primary' => esc_html__( '主导航菜单', 'my-first-theme' ),
        )
    );
    // 添加HTML5标记支持
    add_theme_support(
        'html5',
        array(
            'search-form',
            'comment-form',
            'comment-list',
            'gallery',
            'caption',
            'style',
            'script',
        )
    );
}
add_action( 'after_setup_theme', 'my_first_theme_setup' );

// 注册小工具侧边栏
function my_first_theme_widgets_init() {
    register_sidebar(
        array(
            'name'          => esc_html__( '主侧边栏', 'my-first-theme' ),
            'id'            => 'sidebar-1',
            'description'   => esc_html__( '在此添加小工具。', 'my-first-theme' ),
            'before_widget' => '<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' );

// 加载主题样式表和脚本
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-main-style', get_template_directory_uri() . '/assets/css/main.css', array(), '1.0' );
    // 加载通用JavaScript
    wp_enqueue_script( 'my-first-theme-navigation', get_template_directory_uri() . '/assets/js/navigation.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_first_theme_scripts' );

新增基礎樣式

現在,讓我們在style.css的註釋頭部之後,新增一些基礎CSS來美化你的主題。

推荐阅读 终极WordPress主题开发指南:从零开始搭建自定义WordPress网站主题

/* 基础重置与排版 */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    line-height: 1.6;
    color: #333;
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f9f9f9;
}

header {
    border-bottom: 2px solid #0073aa;
    margin-bottom: 40px;
    padding-bottom: 20px;
}

.entry-title {
    color: #222;
}

.site-main {
    float: left;
    width: 70%;
}

/* 侧边栏样式 */
.widget-area {
    float: right;
    width: 25%;
    padding-left: 5%;
}

/* 页脚样式 */
footer {
    clear: both;
    border-top: 1px solid #ddd;
    margin-top: 60px;
    padding-top: 20px;
    text-align: center;
    color: #666;
}

模組化與模板部件

為了提高程式碼的可維護性和複用性,WordPress鼓勵將重複的頁面部分(如頁頭、頁尾、側邊欄)拆分成單獨的模板部件檔案。

建立頁頭與頁尾部件

建立 (注:此处"建立"可能指某个组织、项目或机构的创立过程。)header.php,包含從<!DOCTYPE html>開始到開啟<main>標籤之前的所有內容。

InterServer 共享主机
虚拟主机的月费为1TB+5TB,价格为2.50美元。首月优惠价为1TB+5TB,价格为0.1美元。优惠码为"tryinterserver"。平台提供461个云应用脚本,一键安装便捷。
<!DOCTYPE html>
<html no numeric noise key 1014>
<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">
    
</head>
<body no numeric noise key 1011>

<div id="page" class="site">
    <a class="skip-link screen-reader-text" href="#primary">跳至主要内容</a>
    <header id="masthead" class="site-header">
        <div class="site-branding">
            
                <h1 class="site-title"><a href="/zh-tw/</?php echo esc_url( home_url( '/' ) ); ?>" rel="home"></a></h1>
                
                <p class="site-title"><a href="/zh-tw/</?php echo esc_url( home_url( '/' ) ); ?>" rel="home"></a></p>
                
                <p class="site-description"></p>
            
        </div>
        <nav id="site-navigation" class="main-navigation">
            'primary',
                    'menu_id'        =&gt; 'primary-menu',
                )
            );
            ?&gt;
        </nav>
    </header>
    <div id="content" class="site-content">

相應地,建立footer.php,包含</div><!-- #content -->之後的所有內容。

    </div><!-- #content -->
    <footer id="colophon" class="site-footer">
        <div class="site-info">
            <p><?php printf( esc_html__( '主题:%1$s', 'my-first-theme' ), '<a href="https://example.com/">我的第一个主题</a>' ); ?></p>
        </div>
    </footer>
</div><!-- #page -->

</body>
</html>

建立 (注:此处"建立"可能指某个组织、项目或机构的创立过程。)sidebar.php來顯示小工具區域。

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

完成這些部件後,你就可以用get_header()get_footer()以及get_sidebar()函式在所有模板檔案中簡潔地呼叫它們了。

总结

透過本指南,你完成了從零開始構建一個基礎WordPress主題的全過程。你學習瞭如何設定開發環境、建立必需的主題檔案(style.css以及index.php),並深入理解了WordPress的模板層級系統,從而建立了針對不同頁面型別(如文章、頁面)的專用模板(single.phppage.php)。你掌握了透過functions.php檔案為主題新增核心功能,如註冊選單、小工具和支援特色影象。最後,你實踐了模組化開發思想,將頁頭、頁尾和側邊欄拆分為可複用的模板部件(header.phpfooter.phpsidebar.php),這極大地提升了程式碼的可維護性。這只是一個起點,在此基礎上,你可以繼續探索自定義文章型別、高階主題選項、響應式設計以及JavaScript互動,逐步構建出功能強大、設計專業的WordPress主題。

常见问题解答(FAQ)

為什麼我的主題在後臺不顯示?

確保你的主題資料夾正確放置在wp-content/themes/目錄下,並且其中的style.css檔案頭部包含格式正確的註釋塊,特別是Theme Name:這一行必須存在且正確。檔案編碼應為UTF-8 without BOM。

如何為我的主題新增自定義Logo支援?

请将下文翻译成中文,并详细说明翻译思路:\n在你的functions.php文件的my_first_theme_setup函式中,新增一行程式碼:add_theme_support( 'custom-logo' );。新增後,使用者就可以在WordPress後臺的“外觀”->“自定義”->“站點身份”中上傳和設定Logo了。你需要在header.php请将下文翻译成中文,并详细说明翻译过程:the_custom_logo()函式來輸出Logo。

修改了functions.php檔案後網站出現白屏怎麼辦?

這通常意味著functions.php檔案中存在PHP語法錯誤。WordPress會因致命錯誤而停止執行。你需要透過FTP或檔案管理器訪問伺服器,將出錯的functions.php重新命名(如改為functions.php.bak),使網站恢復訪問。然後,檢查並修正你的程式碼,再重新上傳正確的檔案。在本地開發環境中進行測試是避免此類問題的好習慣。

怎样让我的主题支持多语言翻译?

你已經在style.css中設定了Text Domain(文字域),並在functions.php的字串中使用了esc_html__( ‘文本’, ‘my-first-theme’ )這樣的翻譯函式。接下來,你需要使用Poedit這類工具,掃描主題檔案中的可翻譯字串,生成.pot模板檔案,然後為每種語言建立對應的.po以及.mo檔案,並將它們放在主題的/languages資料夾中。WordPress會根據站點語言設定自動載入對應的翻譯。