New best practices for child themes in WordPress

It used to be easy to create a child theme in WordPress. With the introduction of WordPress 4.0, it’s become a bit more complicated.

Previously when building a child theme, you would create a new folder (and name) for your theme, include a “style.css” file with a certain header so WordPress would know what you were trying to do, and then call in the stylesheet(s) of the parent theme with an @import statement or two.

No more.

The WordPress Codex file on child themes specifies that best practices now dictate that you not use the @import statement in the child theme “style.css,” but instead enqueue the parent style in your child theme’s “function.php” file, thusly:

<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style', get_stylesheet_uri(), array( 'parent-style' ) );
}

Calling the main theme stylesheet as the “parent” and your child theme stylesheet as the “child” tells WordPress to load your child theme stylesheet after the stylesheet of the main theme. If it’s not already obvious, this means that each child theme will almost certainly have a “functions.php” file, as well as the “style.css” file, and whatever other files you’ll want that make a child theme necessary in the first place.

As an aside, if you simply want to make a few changes to the CSS for the main theme, there are plug-ins that allow you to do this so you don’t have to resort to a child theme. My favorite is JetPack, not only for this feature but also because it has so many great tools — and it comes from the creators of WordPress.

While we’re discussing new best practices for child themes, the Child Themes Codex also talks about “Referencing / Including Files in Your Child Theme.” The recommendation there is:

require_once( get_stylesheet_directory() . '/my_included_file.php' );

I couldn’t get this to work for love or money; having this line in the child theme “function.php” file resulted in the WordPress white screen of death.

But with a little alteration of the code, it works great. Example:

include( get_stylesheet_directory() . '/inc/template-tags.php' );

(If it’s not obvious, I wanted to make a change in the “/inc/template-tags.php” file of my child theme, and then get that loaded instead of the “/inc/template-tags.php” file in the parent theme.)

Advertisements

One thought on “New best practices for child themes in WordPress

  1. followed your guide, not still able to load my /inc/template-tags.php instead of the parent one :/

Comments are closed.