Getting Started with WordPress Theme Development: Build Your First Custom Theme from Scratch

3-minute read
2026-03-12
2026-06-03
2,535
I earn commissions when you shop through the links below, at no additional cost to you.

Basic preparation

Before you start writing code, a suitable environment and a basic understanding are the cornerstones of success. First, you need a local development environment. You can choose integrated software packages such as XAMPP, MAMP, or Local by Flywheel, which can quickly set up PHP, MySQL, and a web server for you. Of course, you can also choose a more flexible approach and manually set up the environment locally. Make sure your PHP version is 7.4 or higher, and MySQL is 5.6 or higher.

Next, you need to create a separate directory for your custom theme. This directory must be located in the WordPress installation directory. wp-content/themes/ under the folder. For example, you can create one named my-first-theme folder. A WordPress theme only needs two files to be recognized by the system:index.php and style.cssAmong them,style.css It is not just a stylesheet; it also includes the file header that defines the theme metadata, which is the theme’s “ID card.”

Create the theme core file

Edit Theme Stylesheet Header

style.css The beginning of the file must be a formatted CSS comment block containing all the information WordPress needs to recognize the theme. This is the part that every theme must be configured correctly.

Recommended Reading From Zero to One: A Complete Guide and Practical Tutorial for WordPress Theme Development

/*
Theme Name: 我的第一个主题
Theme URI: https://example.com/my-first-theme/
Author: 你的名字
Author URI: https://yourwebsite.com
Description: 这是一个入门级的自定义 WordPress 主题,用于学习开发。
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: my-first-theme
*/

Among them, “Text Domain” is used for internationalization, and we will use functions later. __() Or _e() Enable the text in the theme to support multilingual translation.

UltaHost WordPress Hosting
30-day refund guarantee, unlimited bandwidth and database usage, free DDoS protection; purchase for 3 years and get a discount of 50%.

Generate Basic Template Files

index.php It is the theme's default template and also the most important fallback template. When WordPress cannot find a more specific template file (such as single.php), it will be used. One of the most basic index.php It should include the WordPress Loop, which is the core mechanism for outputting post content.

<!DOCTYPE html>
<html no numeric noise key 1022>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
</head>
<body no numeric noise key 1019>
    
    <header id="site-header">
        <h1><a href="/en/</?php echo esc_url( home_url( '/' ) ); ?>"></a></h1>
        <p></p>
    </header>

<main id="main-content">
        
                <article id="post-<?php the_ID(); ?>" no numeric noise key 1011>
                    <h2><a href="/en/</?php the_permalink(); ?>"></a></h2>
                    <div class="entry-content">
                        \n
                    </div>
                </article>
            
            <p></p>
        
    </main>

<?php get_sidebar(); ?>

<footer id="site-footer">
        <p>©</p>
    </footer>
    
</body>
</html>

This template uses several core WordPress functions, such as wp_head(), the_title(), the_content(). function get_sidebar() Will try to load one named sidebar.php The template file for…

Implement template hierarchy and functionality

WordPress uses a set of rules called the “template hierarchy” to determine which template file to use for a specific page. Understanding this hierarchy is key to developing flexible themes. For example, when visiting a blog post, WordPress will look for the following in order:single-post.php -> single.php -> singular.php -> index.phpYou can customize the appearance of different pages by creating these specific files.

Add Featured Image Support to Posts

Modern themes usually support “post thumbnails” (Post Thumbnail). To enable this feature, you need to add the following to your theme’s functions.php Used in the file add_theme_support() Function. First, create it in the theme directory. functions.php The document.

Recommended Reading Practice-Oriented: A Comprehensive Guide to Mastering WordPress Theme Development from Zero to Expert

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

if ( ! function_exists( 'my_first_theme_setup' ) ) :
    function my_first_theme_setup() {
        // 让 WordPress 管理标题标签
        add_theme_support( 'title-tag' );

// 启用文章特色图像支持
        add_theme_support( 'post-thumbnails' );
        // 为文章和页面设置默认特色图像尺寸
        set_post_thumbnail_size( 1200, 800, true );

// 注册一个导航菜单位置
        register_nav_menus( array(
            'primary' => __( '主导航菜单', 'my-first-theme' ),
        ) );
    }
endif;
add_action( 'after_setup_theme', 'my_first_theme_setup' );

Import styles and script files

Properly enqueuing CSS and JavaScript files is a WordPress development best practice, as it avoids resource conflicts and duplicate loading. We do this by wp_enqueue_style() and wp_enqueue_script() implemented with a function. In functions.php Add a new function.

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

// 引入自定义 JavaScript 文件
    wp_enqueue_script( 'my-first-theme-navigation', get_template_directory_uri() . '/js/navigation.js', array(), wp_get_theme()->get( 'Version' ), true );

// 如果评论功能开启且有评论,加载评论回复脚本
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'my_first_theme_scripts' );

Advanced Topics and Best Practices

A complete theme is not just about presenting content; it also needs to consider accessibility, performance, and structure. Separating different page sections, such as the header, footer, and sidebar, into separate template files can make the code easier to maintain.

Separate header and footer templates

Create header.php and footer.php File. Please transfer it. index.php China has become an increasingly important player in the global economy, and its economic influence has been expanding globally. <body> Move all content before the label to header.php</body> Move all content before the label to footer.php. Then, take the original index.php Condensed to:

hosting.com Shared Hosting
High performance with AMD EPYC CPUs, NVMe SSD storage and LiteSpeed, 24/7, 24x7 expert in-house support, advanced security measures including SSL, brute force, malware and DDoS protection, savings of up to 73%
<main id="main-content">
        
                <article id="post-<?php the_ID(); ?>" no numeric noise key 1012>
                    <?php if ( has_post_thumbnail() ) : ?>
                        <div class="post-thumbnail">
                            <?php the_post_thumbnail(); ?>
                        </div>
                    
                    <h2><a href="/en/</?php the_permalink(); ?>"></a></h2>
                    <div class="entry-content">
                        \n
                    </div>
                </article>
            
            <p></p>
        
    </main>

Create a sidebar template.

Similarly, create one sidebar.php the file and use the dynamic sidebar function in it dynamic_sidebar(). First, you need to functions.php Use it in Chinese register_sidebar() Registers a sidebar widget area.

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' );

Then, in sidebar.php Call it in:

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

summarize

By following the steps in this article, you have successfully built a basic but fully functional custom WordPress theme from scratch. You have learned to create the core files, understand the template hierarchy, and use functions.php Add theme functionality and organize and load assets according to best practices. This theme has basic features such as displaying posts, supporting featured images, and registering menus and sidebars. Starting from this point, you can continue exploring more complex template files (such as page templates and category templates), custom post types, the Theme Customizer API, and more, gradually building a powerful, professionally designed WordPress theme. Remember, practice is the key to learning; trying to modify the code and observing the changes is the best way to solidify your knowledge.

Recommended Reading Beginner's Guide to WordPress Theme Development: Creating Custom Themes from Scratch

FAQ Frequently Asked Questions

What should I do if my theme doesn't appear in the backend?

Please first check whether your theme folder is in the correct location wp-content/themes/ in the directory. Then, confirm style.css Is the theme information header (CSS comment) at the top of the file correctly formatted, especially the “Theme Name:” line, which must be present and properly formatted. Any spelling errors or formatting issues may prevent WordPress from recognizing your theme.

What should I do if modifying the functions.php file causes the website to show a white screen?

“A white screen freeze is usually functions.php It is caused by syntax errors in the file (such as missing semicolons or parentheses) or fatal errors. The quickest solution is to use FTP or a file manager to access your server and locate the erroneous functions.php Renaming a file (for example, changing its name to…) functions.php.bak), so WordPress will ignore that file and restore access to the website. Then, you can check and fix the code errors.

InterServer Shared Hosting
Shared hosting $2.50 USD per month , first month $0.1 USD promo code tryinterserver, 461 cloud apps scripts, one click install.

How do I add a page template to my theme?

To create a custom page template, first create a new PHP file in your theme directory, for example template-fullwidth.phpAt the very top of this file, add the following specific template comment:

<?php
/**
 * Template Name: 全宽页面
 */

Then, you can write your HTML and PHP code in this file, remember to use get_header(), get_footer() etc. After saving, when editing or creating a page in the WordPress admin dashboard, you will be able to see and select “Full Width Page” from the “Template” dropdown under “Page Attributes”.

主题开发中 get_template_part() 函数有什么用?

get_template_part() Functions are a powerful tool for modularizing code in WordPress theme development. Their purpose is to load a specific template part in your theme. For example, in the loop, you can use get_template_part( 'content', get_post_format() ); Let's load it. content.php Or more specifically content-video.php files. This greatly improves code reusability and maintainability, allowing you to easily create different display templates for different types of article content.