WordPress Child Themes

When making changes to a an existing WordPress template, it’s recommended to create a child theme. This will make it possible to update the parent template while preserving your modifications. Only 2 files are required, style.css and functions.php. Every other file can be overridden. Note that functions.php in your child theme will be loaded before the functions.php from the parent theme. This makes it possible to override specific functions (if the parent theme has built in function_exists() checks).

├── example-theme/
│   ├── style.css
│   ├── functions.php
│   ├── index.php
│   └── [etc.]
└── example-theme-child/
    ├── style.css
    ├── functions.php
    ├── js/
    │   └── custom_script.js
    └── languages/
        └── nl_NL.mo

 Theme Name:   Example Theme Child
 Theme URI:    http://example.com/example-theme-child/
 Description:  Example Theme Child Theme
 Author:       Me
 Author URI:   http://example.com
 Template:     example-theme
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         child, theme, example
 Text Domain:  example-theme

Replace Example Theme Child and example-theme-child with your own name, replace example-theme with the parent theme’s (directory) name. Check your parent theme’s text domain, this might not be the same.

 * Enqueue parent(!) stylesheet(s)
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );

 * Enqueue your scripts (with jQuery as a dependency)
function theme_enqueue_scripts() {
    wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', array( 'jquery' ) );
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );

Note: the snippet above uses get_stylesheet_directory() and get_template_directory_uri(), they are not the same! The first will return the child theme’s path and the latter the parent theme’s path!

You can merge your custom labels with the parent theme’s labels. This way you can both add new labels and override existing ones.
Add the following lines to your functions.php and change parent-theme with your parent theme’s text domain. Put the mo’s (and po’s) in a language folder, for example for Dutch languages/nl_NL.mo.

add_action( 'after_setup_theme', function () {
    // load custom translation file before the parent theme
    load_child_theme_textdomain( 'parent-theme', get_stylesheet_directory() . '/languages' );
} );

Note: the snippet above uses get_stylesheet_directory() instead of get_template_directory_uri(), because the first will return the child theme’s path and the latter the parent theme’s path!

More info about developing child themes at the WordPress Codex.

Leave a Reply