Tuesday, September 6, 2016

WordPress Child Themes: A Complete Guide to the Core Concepts

This week's article is a chapter from Up and Running, our multimedia guide to WordPress development, on the subject of WordPress child themes. The intent of this chapter is to get you up-to-speed on all of the core concepts of child themes. Download this Chapter as a PDF

If you'd like to read the chapter as a PDF from the e-book, feel free to download it here. Enjoy!

About Up and Running

In Up and Running, we give this chapter's detailed treatment to all the key concepts of WordPress development. If you're interested, check it out! And we agree with a buyer tweet from last week:

If anyone is on the fence about "Up and Running", don't be! The vids and eBook are incredibly helpful for new devs!

Key Takeaways:
  • A child theme is a specially registered WordPress theme that inherits most of its properties from a declared parent theme. A major reason to create a child theme is to be able to update the parent theme without losing desired customizations.
  • style.css is the only mandatory file in a child theme. The general rule is that child theme files override parent theme files if they exist.
  • To properly use child themes, you'll need to know how to include the parent theme's style.css; how the WordPress template hierarchy responds to child themes; and under what circumstances you can overwrite existing functions in functions.php.
  • A WordPress child theme is a WordPress theme that depends on a "parent" theme—which could be any other theme already in existence, as long as that theme isn't itself a child theme.

    A child theme inherits everything about its parent—and then it only changes what it needs to change. So you could set up a child theme that's identical to its parent, simply by importing the parent theme's stylesheet (we'll cover that later) and making no other changes.

    Why Use a Child Theme?

    If you make changes to a WordPress theme, and then update the theme, you lose your changes.

    Themes often update, and for very good reasons: important new features, bugfixes, and (especially) crucial security patches, as well as other reasons. There's no way to update "just part of" a theme—so if you make changes to a third-party theme (say a commercial theme) and then update that theme to a new version, your changes are gone.

    Child themes let you make only the changes you need to make, all while letting the parent theme continue to update under you. This is the major reason why they exist.

    As you get used to working with child themes, you'll discover another reason to use them: they're really convenient. It's much easier to write only the changes you need to a clean file (for example, style.css or functions.php) than it is to dive into an existing theme and start pulling wires. So child themes are not only necessary, they're nice.

    How to Make a Child Theme

    To make a child theme, you create a new theme. Normal themes (themes that can become parent themes) have two required files: style.css and index.php. Child themes, however, have only one: style.css. This is because they inherit the parent's index.php by default.

    Registering a Child Theme and the "Template: " Line

    Child themes are registered like normal themes, in a comment block in style.css. There's one new field, though: Template: . This line is mandatory for every child theme, and corresponds to the name of the folder in which the parent theme is located.

    Here's an example child theme comment block:

    /* Theme Name: Twenty Fifteen Child Theme URI: http://upandrunningwp.com/ Description: Child theme for the Twenty Fifteen theme Author: WPShout Author URI: http://wpshout.com/ Template: twentyfifteen Version: 1.0.0 */

    This goes in style.css in a new theme folder:

    And gives this result:

    Click to enlarge

    Notice, again, that the parent theme's "nice name" is Twenty Fifteen, but the name of its directory is twentyfifteen. That's the one we need to write after Template: .

    Pulling in the Parent Theme's Stylesheet

    If we activate our Twenty Fifteen Child theme right now, our site won't look anything like Twenty Fifteen. On the contrary, it'll look like an absolute disaster:

    Why? Because WordPress is no longer listening to the parent theme's style.css. The child's style.css is the primary stylesheet for the site now—and since it has nothing in it, the site looks (and is!) totally unstyled.

    There are several good ways to solve this problem; we'll cover two.

    Option One: @importing the Parent Theme's style.css from the Child Theme's style.css

    This first solution is a single line in the child's style.css:

    @import url("../twentyfifteen/style.css");

    That's better! This simply uses CSS's @import directive to pull all the contents of the parent theme's style.css file into your child theme's style.css. Now your site's looking the way it did before, and you can write your own styles below.

    Option Two: enqueueing the Parent Theme's style.css in the Child Theme's functions.php

    This solution uses a good old wp_enqueue_style() call, in the functions.php of the child theme:

    /* Environment: functions.php of a child theme whose parent is twentyfifteen */ function wpshout_enqueue_twentyfifteen_stylesheet( ) { wp_enqueue_style( 'twentyfifteen', get_template_directory_uri() . '/style.css' ); } add_action( 'wp_enqueue_scripts', 'wpshout_enqueue_twentyfifteen_stylesheet' );

    One thing to note here is the use of the function get_template_directory_uri(). This function refers to the root directory of the current theme if called in a normal theme, and to the root directory of the parent theme if called in a child theme. So with this function you don't always know whether you're talking to your own theme or its parent—not too useful in general, but it's what we need here, since we for sure want to be talking to the parent.

    Why would you load the parent's style.css in this way? The PHP route turns out to be a little bit quicker, because CSS @imports force additional server requests. Remember, it's your browser, not the server, that can figure out what @import even means. When it does, it has to then turn around and ask the server—a second time—for the stylesheet it's supposed to be @importing.

    This performance differential is not usually crucial for most websites and most hosting environments, so either of these methods is a great way to get your parent themes loaded up. However, because of its better performance, the wp_enqueue_style() solution is better coding practice, so we recommend you use that when possible.

    How Child Theme and Parent Theme Files Interact

    We've already seen that the child's style.css takes over for the parent's. Let's look more closely at an important question: under what circumstances do the child theme's files substitute for the parent theme's?

    Here's a diagram that breaks that question down for each piece of a child theme:

    Click to enlarge

    In most cases, child theme files simply override identically-named files in the parent.

    In most cases, child theme files simply override identically-named files in the parent. The two noteworthy exceptions are:

  • Files in the WordPress template hierarchy
  • functions.php
  • Files in the WordPress Template Hierarchy

    When you add a child theme, WordPress still steps through the template hierarchy as it always does, with one difference: at every step in the hierarchy, it first checks in the child theme, then in the parent theme.

    Traversing the Template Hierarchy with a Child Theme: A First Example

    Let's say we're about to display our About page, a post of type Page. This Page's slug is about and its id is 2.

    In this example, let's say that the parent theme has two template files: page.php and index.php. The child theme has just one template file: index.php.

    Here's how WordPress will decide which template to display:

  • page-$slug.php:
  • Does the child theme have a file named page-about.php? (No)
  • Does the parent theme have a file named page-about.php? (No)
  • page-$id.php:
  • Does the child theme have a file named page-2.php? (No)
  • Does the parent theme have a file named page-2.php? (No)
  • page.php:
  • Does the child theme have a file named page.php? (No)
  • Does the parent theme have a file named page.php? (Yes)
  • In this case, WordPress will use the parent theme's page.php template to display the page.

    A Second Example

    Now let's imagine the same situation, but that the child theme does have a page.php as well:

  • page-$slug.php:
  • Does the child theme have a file named page-about.php? (No)
  • Does the parent theme have a file named page-about.php? (No)
  • page-$id.php:
  • Does the child theme have a file named page-2.php? (No)
  • Does the parent theme have a file named page-2.php? (No)
  • page.php:
  • Does the child theme have a file named page.php? (Yes)
  • In this case, the child theme's page.php will override the parent's, and WordPress will use the child's page.php to display the page.

    functions.php

    A child theme's functions.php loads before its parent's.

    functions.php is a very special case: it loads before the parent's functions.php. Depending on how the parent theme is written, this can play out in two very different ways:

    Themes with Pluggable Functions

    Careful parent theme authors use function_exists() checks to let the child's functions.php overwrite specific parent theme functions.

    PHP has a function titled function_exists(). Much like WordPress's conditional tags, it returns a boolean—either true or false—depending on whether the function it's given to look for exists or not.

    Careful parent theme authors wrap all their functions in if ( ! function_exists() ) {}. In plain language, this means "if function doesn't exist": the ! means "not," and so the if-statement is false if the function does exist, and true otherwise. Theme developers use it as follows:

    /* Environment: Parent theme's functions.php */ // Only run if wpshout_filter_example() does not already exist if ( ! function_exists( 'wpshout_filter_example' ) ) { function wpshout_filter_example( $title ) { return 'Hooked: '.$title; } add_filter( 'the_title', 'wpshout_filter_example' ); }

    if ( ! function_exists( ) ) checks create what are called pluggable functions.

    This creates what are called pluggable functions: functions that the child theme's functions.php can overwrite. How does the child theme overwrite them? Simply by registering those functions, since the child's functions.php executes first! So the child theme author could write:

    /* Environment: Child theme's functions.php */ function wpshout_filter_example( $title ) { return 'Hooked by Child! ' . $title; } add_filter( 'the_title', 'wpshout_filter_example' );

    Here, the child's wpshout_filter_example() will execute—and the parent's won't, since ! function_exists( 'wpshout_filter_example' ) now evaluates to false.

    How to Work With Parent Themes That Don't Use Pluggable Functions

    This situation makes life more difficult for child theme authors. Let's take our same example: the child theme functions.php registering a function called wpshout_filter_example() that also exists in the parent theme's functions.php.

    The child theme's function registers just fine. Then, the parent theme's functions.php registers a function by the same name.

    PHP really doesn't like this. Here's a real-world example, using a Twenty Fifteen function and a child theme of Twenty Fifteen:

    So if the parent theme isn't doing function_exists() checks, you need to avoid duplicate function names at all costs.

    This also means that any custom PHP functionality the parent theme adds is simply bound to execute. If you want to change or remove pieces of that functionality, you'll have to do so manually, one step at a time, by writing your own functions that dequeue unwanted stylesheets, and so on.

    What We've Learned

    We now know the basics of child themes, and how and why to use them. To change existing themes—for example, commercial themes on client sites—you'll be using child themes constantly, so this is a really great piece of knowledge to have under your belt.

    Summary Limerick

    When child themes are born from their parent,The family ties are apparent:What they don't overrideIt will swiftly provide,So inheritance comes in inherent.

    Quiz Time!
  • Child themes exist so that:
  • Theme customizations can persist when the themes themselves update
  • People without technical expertise can easily customize themes
  • Themes are easy to restore should they become lost or corrupted
  • It's possible to make the following themes into parent themes:
  • Specially coded existing themes
  • Existing themes with a functions.php
  • Any theme that is not already a child theme
  • If a child theme author names a function identically to a function in the parent theme which is not wrapped in a if ( ! function_exists() ) {} check, then:
  • Both functions will execute
  • Neither function will execute
  • PHP will throw a fatal error
  • Answers and Explanations
  • A. Theme updates often provide needed security fixes as well as new features, and would overwrite theme customizations without the child theming process.
  • C. There are no special requirements for parent themes; however, there are no "grandchild" themes.
  • C. PHP cannot process duplicate function names. With the if ( ! function_exists() ) {} check, the child theme's function will execute and the parent theme's will not; this allows child theme authors to selectively replace parent theme functions, which is why if ( ! function_exists() ) {} is good practice in theming generally.

  • Source: WordPress Child Themes: A Complete Guide to the Core Concepts

    No comments:

    Post a Comment