準備工作與環境搭建
在開始編寫代碼之前,你需要一個合適的開發環境。這包括一個本地的服務器環境(如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文件,並輸入以下基礎信息:
/*
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-hk/</?php echo esc_url( home_url( '/' ) ); ?>"></a></h1>
<p></p>
</header>
<main>
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
?>
<article>
<h2><a href="/zh-hk/</?php the_permalink(); ?>"></a></h2>
<div></div>
</article>
<?php
endwhile;
else :
echo '<p>暂无文章。</p>';
endif;
?>
</main>
<footer>
<p>©</p>
</footer>
<?php wp_foot(); ?>
</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">
<?php
while ( have_posts() ) :
the_post();
?>
<article id="post-<?php the_ID(); ?>" no numeric noise key 1009>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<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.php、sidebar.php以及footer.php文件,這是實現代碼複用和模塊化設計的關鍵。
創建頁面模板
對於靜態頁面(如“關於我們”),WordPress會尋找page.php。創建page.php,其結構與single.php類似,但通常不顯示分類、標籤和發佈時間等元信息。
<main id="primary" class="site-main">
<?php
while ( have_posts() ) :
the_post();
?>
<article id="post-<?php the_ID(); ?>" no numeric noise key 1005>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header>
<div class="entry-content">
</div>
</article>
<?php
endwhile;
?>
</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' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</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>標籤之前的所有內容。
<!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">
<?php
if ( is_front_page() && is_home() ) :
?>
<h1 class="site-title"><a href="/zh-hk/</?php echo esc_url( home_url( '/' ) ); ?>" rel="home"></a></h1>
<?php
else :
?>
<p class="site-title"><a href="/zh-hk/</?php echo esc_url( home_url( '/' ) ); ?>" rel="home"></a></p>
<?php
endif;
$my_first_theme_description = get_bloginfo( 'description', 'display' );
if ( $my_first_theme_description || is_customize_preview() ) :
?>
<p class="site-description"><?php echo $my_first_theme_description; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p>
</div>
<nav id="site-navigation" class="main-navigation">
<?php
wp_nav_menu(
array(
'theme_location' => 'primary',
'menu_id' => 'primary-menu',
)
);
?>
</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.php, page.php)。你掌握了通過functions.php文件為主題添加核心功能,如註冊菜單、小工具和支持特色圖像。最後,你實踐了模塊化開發思想,將頁頭、頁腳和側邊欄拆分為可複用的模板部件(header.php, footer.php, sidebar.php),這極大地提升了代碼的可維護性。這只是一個起點,在此基礎上,你可以繼續探索自定義文章類型、高級主題選項、響應式設計以及JavaScript交互,逐步構建出功能強大、設計專業的WordPress主題。
常见问题解答(FAQ)
為什麼我的主題在後台不顯示?
確保你的主題文件夾正確放置在wp-content/themes/目錄下,並且其中的style.css文件頭部包含格式正確的註釋塊,特別是Theme Name:這一行必須存在且正確。文件編碼應為UTF-8 without BOM。
如何為我的主題添加自定義Logo支持?
在你的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會根據站點語言設置自動加載對應的翻譯。
接下来,我该怎么做呢?
延伸阅读与实用知识
下方这些内容与本文主题相关,适合继续深入阅读。建议先从与你当前问题最相关的文章开始看起,然后再逐步扩展到相关主题,这样通常效果会更好。