Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 5 • The Child Theme Concept 127


So what’s the verdict: Are child themes a good idea? In most cases, yes. If you discover you’re
creating a brand-new theme rather than making standalone changes to an existing one, you’re
better off creating what you need from scratch, or rather, from that core theme you may have
ended up creating by now.


COMMON ISSUES TO KEEP IN MIND


There really are just two things with child themes that can cause confusion. The first is purely
user-based, and that is the fact that the child theme just won’t work unless the parent theme is
in the wp-content/themes/ folder. This is pretty obvious when you think about it, but most
users are used to just uploading a theme and then activating it, and that won’t work with a
child theme unless the parent theme is there. Or, rather, it may work, but it will definitely look
awful and behave badly, too.


The second issue with child themes is technical, and it involves the template path. Most of the
time when you want to point to the theme directory, for example to display an image, you’ll use
get_template_directory_uri() and echo it for use. That won’t work in a child theme,
as the template directory is in fact the parent theme’s directory! Hence this code, to display an
image, would point to the parent theme’s theme folder rather than the child theme’s folder:


<img src="<?php echo get_template_directory_uri(); ?>/images/the-image.gif"
alt="My image" />


Luckily, there is a solution to this. If you use get_stylesheet_directory_uri() rather
than get_template_directory_uri in your child theme, WordPress will look in the
folder with the theme’s style sheet instead. And guess what, that’s your child theme! So the
preceding code would have to be altered to this to work in a child theme:


<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/the-image.gif"
alt="My image" />


This is a common issue, with images suddenly not working or perhaps the wrong one being
displayed because of its existing in the parent theme as well.


When you are working with child themes, it is important to remember that functions pointing
to a template actually refer to the parent theme, not the child theme. The preceding example
illustrates this. It makes a lot of sense, actually, because the child theme uses the parent theme as
a template, whereas a parent theme (or rather, a nonchild theme) is its own template, so to speak.


MANAGING SEVERAL SITES USING CHILD THEMES


If you’re one of those people running your own blog network or just a number of sites built on
the same basic design, then child themes are just right for you. Think about it: You can put
more resources into creating features and deploying new functionality in the parent theme
and store all the custom stuff for the various sites in child themes. That way, you’ll speed up
development and make upgrades easier.

Free download pdf