Preparatory work and environment setup
Before you start writing code, you need a suitable development environment. This includes a local server environment (such as XAMPP, MAMP, or Local by Flywheel) as well as a code editor (such as VS Code, PhpStorm, or Sublime Text). Make sure that your local environment supports PHP (version 7.4 or higher) and MySQL/MariaDB.
Next, you need to go to the WordPress installation directory.wp-content/themesCreate a new folder inside the existing folder; this will become your theme directory. For example, you can create a folder named…my-first-themeThis is the folder that contains all your theme files. It can be considered the “home” for all your theme-related materials.
The most basic files of a WordPress theme consist of only two:style.cssandindex.phpAmong them,style.cssIt's not just a style sheet; it's also the “identity card” of the theme. It communicates metadata about the theme’s name, author, description, and more to WordPress through the comment information in the file header.
Recommended Reading An in-depth analysis of WordPress theme development: a core technical guide from beginner to expert。
Create a theme information file.
In your theme folder, create…style.cssFile, and enter the following basic information:
/*
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
*/ This comment is necessary. WordPress works by reading…Theme NameThis line is used to identify and display your theme in the background theme list. Other information, such as…Text DomainThis is in preparation for internationalization (translation).
Create the core template file
Next, create the most basic version of it.index.phpThe file… Even if the file is currently empty, as long as…style.cssOnce the information is complete, your theme will appear in the “Appearance” -> “Themes” list in the WordPress admin panel and can be activated. Now, let’s…index.phpWrite the simplest HTML structure into it to display the blog title and article content.
<!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="/en/</?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="/en/</?php the_permalink(); ?>"></a></h2>
<div>\n</div>
</article>
<?php
while (have_posts()) {
the_post();
if (have_posts()) {
echo '<p>There are no articles yet.</p>';
}
}
?>
</main>
<footer>
<p>©</p>
</footer>
<?php wp_foot(); ?>
</body>
</html> This code utilizes several core functions from WordPress.模板标签For examplebloginfo()、the_title()、the_content(). functionwp_head()andwp_foot()These are crucial hooks that allow the WordPress core, plugins, and other scripts to insert necessary code at the beginning and end of a page.
Understanding Template Hierarchy and Creating Core Templates
WordPress uses a set of tools and systems known as…模板层级The rules determine which template file should be used to render a specific page request. This is one of the most fundamental concepts in theme development. In simple terms, WordPress starts by looking for the most specific template file; if it doesn’t exist, it falls back to a more general template, and ultimately…index.php。
Recommended Reading An Introduction to WordPress Theme Development: Building Your First Custom Theme from Scratch。
Create a template for the article details page.
When a user visits a single article, WordPress will prioritize searching for…single-post.phpIf it does not exist, then use it.single.phpAnd finally, the most important thing is...index.phpLet's create one.single.phpThis is designed specifically to control the display of individual articles.
<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">
Published on: | Author:
</div>
</header>
<div class="entry-content">
\n
</div>
<footer class="entry-footer">
分类:
</footer>
</article>
<?php
// 上一篇/下一篇导航
the_post_navigation();
// 评论模板
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile;
?>
</main> This template introduces three important template components:get_header()、get_sidebar()andget_footer()They are used respectively for introducing…header.php、sidebar.phpandfooter.phpFiles are the key to achieving code reuse and modular design.
Create a page template.
For static pages (such as “About Us”), WordPress will look for…page.phpCreatepage.phpIts structure is similar to…single.phpSimilar, but usually does not display metadata such as categories, tags, and publication dates.
<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">
\n
</div>
</article>
<?php
endwhile;
?>
</main> Implementing theme functionality and styling
A complete theme not only requires a template file but also needs to be implemented or configured through additional processes (e.g., using specific tools, following development guidelines, etc.).functions.phpUse the file to add features, register menus, and manage the toolbar area, and then proceed with the necessary steps.style.cssAdd styles.
Theme Feature Function File
Create a file in the root directory of your theme.functions.phpThis file is automatically loaded during theme initialization and is used to store all custom PHP functions and hooks.
<?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' ); Add basic styles
Now, let’s move on to…style.cssAfter the comment header, add some basic CSS to beautify your theme.
Recommended Reading The Ultimate Guide to WordPress Theme Development: Create a Custom WordPress Website Theme from Scratch。
/* 基础重置与排版 */
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;
} Modularity and template components
To improve the maintainability and reusability of code, WordPress encourages the separation of repetitive page elements (such as headers, footers, and sidebars) into separate template component files.
Create header and footer components.
Createheader.php…including content from…<!DOCTYPE html>From start to open<main>All the content before the tag.
<!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">Jump to the main content</a>
<header id="masthead" class="site-header">
<div class="site-branding">
<?php
if ( is_front_page() && is_home() ) :
?>
<h1 class="site-title"><a href="/en/</?php echo esc_url( home_url( '/' ) ); ?>" rel="home"></a></h1>
<?php
else :
?>
<p class="site-title"><a href="/en/</?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">
'primary',
'menu_id' => 'primary-menu',
)
);
?>
</nav>
</header>
<div id="content" class="site-content"> Accordingly, createfooter.phpIncludes</div><!-- #content -->All the content that follows.
</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> Createsidebar.phpThis is to display the gadget area.
<?php
if ( is_active_sidebar( 'sidebar-1' ) ) :
?>
<aside id="secondary" class="widget-area">
<?php dynamic_sidebar( 'sidebar-1' ); ?>
</aside>
<?php
endif;
?> After completing these components, you will be able to use them.get_header()、get_footer()andget_sidebar()The functions are called neatly and concisely in all template files.
summarize
By following this guide, you have completed the entire process of building a basic WordPress theme from scratch. You learned how to set up a development environment and create the necessary theme files.style.cssandindex.phpI gained a deep understanding of WordPress’s template hierarchy system, which allowed me to create custom templates for different page types, such as articles and pages.single.php, page.phpYou have mastered the method of…functions.phpThe file adds core features to the theme, such as a registration menu, utilities, and support images. Finally, you implemented the concept of modular development by breaking down the header, footer, and sidebar into reusable template components.header.php, footer.php, sidebar.phpThis greatly improves the maintainability of the code. This is just the beginning; based on this foundation, you can further explore custom article types, advanced theme options, responsive design, and JavaScript interactions to gradually build a WordPress theme that is both powerful and professionally designed.
FAQ Frequently Asked Questions
Why doesn’t my theme appear in the backend?
Make sure your theme folder is placed in the correct location.wp-content/themes/It is located within the directory, and among its contents…style.cssThe file header contains a block of comments with the correct format, especially…Theme Name:This line must be present and correct. The file encoding should be UTF-8 without the BOM (Byte Order Mark).
How to add custom logo support to my theme?
In yourfunctions.phpThe document'smy_first_theme_setupIn the function, add a line of code:add_theme_support( 'custom-logo' );After adding it, users will be able to upload and configure their Logo in the WordPress backend under “Appearance” -> “Customize” -> “Site Identity”. You need to…header.phpUse it in Chinesethe_custom_logo()A function is used to output the Logo.
What should I do if the website shows a blank screen after I modified the functions.php file?
This usually means…functions.phpThere are PHP syntax errors in the file. WordPress will stop executing due to these fatal errors. You need to access the server via FTP or a file manager and remove the problematic code.functions.phpRename (for example, to…)functions.php.bakThis will allow the website to be accessible again. Then, check and fix your code, and re-upload the correct files. It’s a good habit to test in your local development environment to avoid such issues.
How can I make my theme support multi-language translation?
You have already done it.style.cssIt has been set in the middle.Text Domain(Text field), and infunctions.phpThe string used contains…esc_html__( ‘文本’, ‘my-first-theme’ )Such a translation function. Next, you need to use tools like Poedit to scan the translatable strings in the theme files and generate the necessary translation data..potFirst, create a template file, and then create corresponding ones for each language..poand.moFiles, and place them in the topic’s directory./languagesThe files are located in the folder. WordPress will automatically load the corresponding translations based on the site’s language settings.
What's next, what's next?
Extended reading and practical knowledge
The following are related to the topic of this article and are suitable for further in-depth reading. Prioritize starting with the article that is closest to your current problem, and gradually expanding to surrounding topics usually works better.
- One-stop website construction solution: A comprehensive guide for implementing a website from scratch to its launch.
- Preface: Why choose WordPress for development?
- The Ultimate Guide to Website Construction: A Comprehensive Process for Building Professional Websites from Scratch
- How to choose and customize the perfect WordPress theme for you
- How to Choose the Best WordPress Theme: A Comprehensive Buying Guide from Design to Performance