WordPress Development: Introduction to Child Themes
Using a Child theme within WordPress can unlock the door to the vision you have for your site. Welcome to the WordPress Development Series. In this training we will look at an introduction to child themes.
Why use a child theme?
A child theme allows for modifying a parent theme: whether that's CSS, templates or theme functionality. This allows for parent theme updates, without worry of losing theme changes.
What files are needed for a child theme?
For a child theme to work, only a single file, style.css, is needed, with a commented header tag to show it's a child theme. However, we will want to pull in the parent theme's style.css, using a functions.php file.
Style.css Basics
The template header tag is what makes a theme work as a child theme. What you use for the template tag is the value set for the Text Domain tag in the parent theme. For example, the text domain for the TwentyTwenty Two theme is twentytwentytwo. So the template tag for your child theme would be setup as Template: twentytwentytwo
While not required to make the child theme work, other tags are suggested at a minimum. These include Theme Name, Version, Author, and Author URI. We place these tags at the top of the style.css inside a comment block opening with a /* (forward slash star) and closing with a */ (star forward slash)
/* Theme Name: Child Theme Name Description: Child Theme for Site Name Author: Author Name Author URI: https://authorsite.com Template: parent_text_domain Version: 1.0.0 */
A link to find out more information about stylesheet comment headers is provided below.
Function.php to pull in parent theme CSS
While we won't need code to pull in the CSS for the child theme, we will for the parent. This code will go into the child theme's functions.php file. The small block of code hooks into wp_enqueue_scripts to enqueue the parent theme's style.css.
<?php
function ttt_parent_enqueue_styles() {
// handle, source, dependents, version, media
wp_enqueue_style( 'twentytwentytwo', // handle
get_template_directory_uri() . '/style.css', // source
'1.0.0' // version
);
}
# Enqueue Frontend Styles & Scripts
add_action( 'wp_enqueue_scripts', 'ttt_parent_enqueue_styles' );
This code is provided below, as well as a link to learn more about both wp_enqueue_scripts and wp_enqueue_style.
Switching to the child theme will appear the same, as we have only laid the foundation. The use of a child theme allows for updates to the parent, while keeping the desired changes. we will build upon the basics later in this series.