How to Build a WordPress Theme from Scratch: First Steps

Share this article

How to Build a WordPress Theme from Scratch: First Steps

WordPress themes give WordPress users the ability to completely change the look of a WP website, as well as add functionality to it. In this three-part series, we’ll introduce WordPress themes, showing how they work, how they’re structured, the PHP architecture behind them, and other relevant information. We’ll then embark on a journey to build a WordPress theme.

This first article prepares us for this journey by discussing the theory behind WordPress themes.

A Word or Two on the Basics

WordPress was conceived as a blog engine, or a simple, blogging-oriented content management system. It was initially released in 2003, by Matt Mullenweg and Mike Little. Ever since then, its user base hasn’t stopped growing. WordPress is a PHP-powered web application that uses MySQL as its database, and is usually run behind a server program, such as NGINX or Apache.

WordPress is basically just a bunch of PHP files that work together as an application. A PHP interpreter uses these files to produce web pages to web visitors. It produces HTML, to be more precise.

The role of the templating engine of WordPress is to enable us to write (primarily) presentational instructions — instructions on how exactly to structure and style the HTML content that WordPress will output. These instructions are encapsulated in WordPress themes.

Each theme consist of a folder with PHP, CSS, and sometimes JavaScript files. The files that every WordPress theme must have — at the minimum — are style.css and index.php. This is the technical minimum required for the theme to function, but no serious WordPress theme stays with only these two files.

Basic template and Partials Files

The minimum index.php file catches all the queries that don’t have their respective specialized template files within a theme. front-page.php, home.php, page.php, taxonomy.php, author.php, archive.php are some of the templates that we can use in our themes to further structure specific pages or queries in our theme.

For example, the archive.php file will specify the HTML output structure when a visitor requests some of the pages that display list of posts. page.php will specify how to display individual pages, and so on.

Partials files encapsulate repeatable parts of pages in WordPress website. For example, the header and footer are usually consistent across all pages on a website, so WordPress themes separate these page parts into header.php and footer.php. comments.php will be used to display comments wherever applicable.

These files are then required from the template files that we explained.

This way, we adhere to the DRY principle, and don’t repeat the code in all those files.

Template Hierarchy

In the WordPress templating system, there’s a hierarchy of template files that WordPress will try to use for each request. This hierarchy is based on specificity. WordPress will try to use the most specific file for each request, if it exists. If it doesn’t exist, it will look up the next, less specific file, and so on.

To explain this on a page request — when the visitor visits a specific page on a WordPress website — WordPress will first try to find the template the page author assigned to it in the wp-admin backend. That can be a completely custom template file, even completely static.

If there’s no such template, or it wasn’t assigned, WordPress will try to find a template file with a slug of that particular page in its filename. That would look like page-mypageslug.php — whatever our mypageslug may be.

The next file WordPress will try to use will be a file with that particular page’s ID in its filename — like page-48.php.

If none of those page-specific files exist, WordPress will try to use page.php — used for all the pages, unless otherwise specified.

If it doesn’t find page.php, it will try to use singular.php. This template file is used when — for postssingle.php is not found, and for pages when page.php is not found.

Now, if none of these are found in our page request example, WordPress will fall back to index.php.

This, briefly, explains the WordPress template hierarchy. All of these template files we mentioned will usually incorporate (require) partials like header.php, footer.php and others as needed. They can also specify their specific partials to use — for example, a page-specific header.

The next thing you need to be familiar with to understand theming is the WordPress post type.

WordPress Post Types

The content in WordPress exists in the form of post types. The built-in types are posts and pages. These are the logical ones. WordPress also has a built-in attachment post type, navigation menus and revisions. These are also, technically, post types.

We can also specify our own post types, whether in our themes or our plugins. We need use the following:

register_post_type( $post_type, $args )

Here, we specify the post type name, how it’s structured, how it’s represented in wp-admin, and so on.

When we have this defined, we can also create template files specific for this post type. Custom post types, like pages and posts, have their own template hierarchy.

More about the template hierarchy can be found here.

style.css

style.css is a crucial file in every WordPress theme, and its function goes beyond styling. This file is used to provide basic theme information to WordPress. Without this, WordPress would not be able to register a theme as a theme.

The WordPress Codex provides more information about all the details of this file. For the sake of brevity, we’ll review just some of them. In this CSS file’s header comments, we provide WordPress information on the following:

  • theme name
  • author
  • description
  • theme URI
  • version
  • license
  • and other details

WordPress uses these details to display the theme properly in the back end.

The meta header in the Twenty Seventeen theme, for example, looks like this:

/*
Theme Name: Twenty Seventeen
Theme URI: https://wordpress.org/themes/twentyseventeen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Seventeen brings your site to life with header video and immersive featured images. With a focus on business sites, it features multiple sections on the front page as well as widgets, navigation and social menus, a logo, and more. Personalize its asymmetrical grid with a custom color scheme and showcase your multimedia content with post formats. Our default theme for 2017 works great in many languages, for any abilities, and on any device.
Version: 1.7
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: twentyseventeen
Tags: one-column, two-columns, right-sidebar, flexible-header, accessibility-ready, custom-colors, custom-header, custom-menu, custom-logo, editor-style, featured-images, footer-widgets, post-formats, rtl-language-support, sticky-post, theme-options, threaded-comments, translation-ready

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you’ve learned with others.
*/

This said, style.css file is, obviously, used to style our WordPress pages.

WordPress Action and Filter Hooks

WordPress — and WordPress themes and plugins — heavily rely on action hooks and filter hooks. These are part of an event-riven architecture. A simple explanation of this would be that, in the process of execution of the page connected to visitors’ web request, there are certain registered points — hooks — that enable us to fire actions at those points. We hook PHP functions to those points to be executed. Those are action hooks. Filter hooks are focused on processing — changing — pieces of data within the execution cycle. So, if the filter hook is registered for any piece of data (PHP variable), we can hook our own function and change, or process, this piece of data.

Although unorthodox, compared to the omnipresent MVC software pattern, the reliance on the hook system in WordPress has played a big role in the popularization of WordPress, as it has made it very simple to plug new functionalities into it, without the need to touch — or even to deeply understand — the core codebase itself.

Hooks are explained here at greater length, and we’ll delve into it more in other parts of this guide.

The Loop

The Loop is the elementary part of the WordPress request cycle. As the WordPress Codex puts it:

The Loop is PHP code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags.

The WordPress loop is, basically, a PHP while loop that displays posts according to visitors’ request, and specified criteria in the template file in which it’s specified.

Within the loop, whether it outputs just a single post or a page, or a list of them, we can output various parts of the post, like title and content. We can specify any HTML output or structure we want. We can also use conditional tags, and so on.

The most rudimentary example of the loop might look something like this:

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        //
        // Post Content here
        //
    } // end while
} // end if

We can use multiple loops on one page (in which case we need to reset them), and there are specific WordPress functions that exist for use inside it.

Conditional Tags

WordPress Conditional Tags are snippets of PHP code that enable us to display pieces of content only when certain conditions are satisfied. For example, we have the site-wide header.php, which is used on every page of the website, but we may want certain HTML snippets to be displayed only on the home page or some other page.

So, in the first example, we would use is_front_page(), and it would look something like this:

if (is_front_page()){
    # do something
}

There are lots of conditional tags provided, and they allow for big flexibility in WordPress development.

These are the building blocks of WordPress, but there are also taxonomies — which can be built in or custom ones we can specify — and terms within these taxonomies. We use them to categorize and sort our posts.

Theme Structure

At the end of this part, and before we endeavor to create our own theme, we’ll use the WP-CLI tool to scaffold a minimal theme based on Underscores — maintained by Automattic — to get a glance of the typical, minimal WordPress theme structure:

From this, we can get a sense of the way we can structure our theme files, folders, etc.

Conclusion

In this first part of our guide on WordPress theming, we introduced the terminology and the building blocks of WordPress themes, which we’ll use in the following tutorials to build our own WordPress theme.


There are three articles in this series on building a WordPress theme from scratch:

Frequently Asked Questions (FAQs) about Building a WordPress Theme from Scratch

What are the basic files needed to create a WordPress theme?

To create a WordPress theme, you need at least two files: style.css and index.php. The style.css file is where you define your theme’s details and its overall styling. The index.php file is the default template file that WordPress uses to render your site’s content. You can add more files to your theme to customize different aspects of your site, such as header.php for the header area, footer.php for the footer area, and sidebar.php for the sidebar area.

How do I organize my WordPress theme files?

Organizing your WordPress theme files is crucial for maintaining a clean and efficient codebase. Typically, you would have a main theme folder containing all your theme’s files. Inside this folder, you can have subfolders for different types of files. For example, you can have a ‘css’ folder for your CSS files, a ‘js’ folder for your JavaScript files, and an ‘images’ folder for your image files. You can also have a ‘templates’ folder for your template files, such as page.php, single.php, and archive.php.

What is the template hierarchy in WordPress?

The template hierarchy in WordPress is a system that determines which template file will be used to display a certain page on your site. WordPress uses a top-down approach when looking for template files. It starts by looking for a template file that matches the specific query, and if it doesn’t find one, it moves down the hierarchy until it finds a match. For example, for a single post, WordPress would first look for single-{post-type}-{slug}.php, then single-{post-type}.php, then single.php, and finally index.php.

How do I create a child theme in WordPress?

A child theme in WordPress is a theme that inherits the functionality and styling of another theme, known as the parent theme. To create a child theme, you need to create a new theme folder and inside it, create a style.css file. In this file, you need to define your child theme details and import the parent theme’s styles. You can then override the parent theme’s styles and functions by adding your own code to the child theme’s files.

How do I add a custom menu to my WordPress theme?

To add a custom menu to your WordPress theme, you first need to register a new menu location in your theme’s functions.php file using the register_nav_menus function. You can then create a new menu in the WordPress admin area and assign it to the menu location you just registered. Finally, you can display the menu in your theme’s template files using the wp_nav_menu function.

How do I add a widget area to my WordPress theme?

To add a widget area to your WordPress theme, you need to register a new widget area in your theme’s functions.php file using the register_sidebar function. You can then add widgets to this widget area in the WordPress admin area. Finally, you can display the widget area in your theme’s template files using the dynamic_sidebar function.

How do I customize the loop in WordPress?

The loop in WordPress is a PHP code block that displays your site’s content. You can customize the loop by modifying the query parameters or the output HTML. For example, you can use the WP_Query class to create a custom query, or you can use template tags such as the_title and the_content to customize the output.

How do I add custom post types to my WordPress theme?

To add custom post types to your WordPress theme, you need to register a new post type in your theme’s functions.php file using the register_post_type function. You can then create and manage posts of this type in the WordPress admin area. Finally, you can display these posts in your theme’s template files using a custom query.

How do I add custom fields to my WordPress theme?

To add custom fields to your WordPress theme, you can use the Custom Fields meta box in the WordPress post editor, or you can use a plugin like Advanced Custom Fields. You can then display these fields in your theme’s template files using the get_post_meta function.

How do I add a custom logo to my WordPress theme?

To add a custom logo to your WordPress theme, you need to add theme support for custom logos in your theme’s functions.php file using the add_theme_support function. You can then add a logo in the WordPress customizer. Finally, you can display the logo in your theme’s template files using the the_custom_logo function.

Tonino JankovTonino Jankov
View Author

Tonino is a web developer and IT consultant who's dived through open-source code for over a decade. He's also a crypto enthusiast, Linux fan, and moderate libertarian.

WordPresswordpress themesWordPress-hubWordPress-tutorials
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week