Mastering the Fundamentals of WordPress Themes · But there’s more to themes than choosing them,...
Transcript of Mastering the Fundamentals of WordPress Themes · But there’s more to themes than choosing them,...
Mastering the
Fundamentals of
WordPress Themes
How Themes Work, and How to Make
Them Work For You
Brought to you by
Sponsored by
Introduction
WP Shout Page 1 of 39
Contents Introduction ............................................................................................................................................. 2
The Four Languages You Must Know to Understand WordPress Themes ........................................ 3
The Three Core Concepts of WordPress Themes ................................................................................ 8
Demystifying “The Loop” in WordPress ............................................................................................... 12
Understanding the WordPress Template Hierarchy .......................................................................... 16
Make Your Themes Better By Getting to Know get_template_part()................................................ 19
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care ........... 23
How to Link to Your WordPress Theme Resources ........................................................................... 27
Four Things a WordPress Theme Shouldn’t Do .................................................................................. 30
Dealing with Theme Creep ................................................................................................................... 34
Always Use a Child Theme! ................................................................................................................... 36
Summary ................................................................................................................................................ 39
Introduction
WP Shout Page 2 of 39
Introduction
WordPress is the most powerful website builder and content management system in the world.
There, we said it.
Much of that power comes from WordPress’s thorough and ingenious use of themes, which can
give users a huge head start toward creating exactly the site look-and-feel they’re after.
But there’s more to themes than choosing them, setting them up, and selecting theme options.
The theme paradigm offers a lot of power and flexibility to people with a bit of technical savvy:
WordPress developers and empowered WordPress site owners.
Mastering the Fundamentals of WordPress Themes aims to help you become one of them. We’ll be
lifting the hood on WordPress themes—so you can start to see how they work, how they fit
together, and how you can build and modify them to meet your own needs.
We’ll be covering the following:
Core principles: what WordPress themes are, what they do, and how they work in their
fundamentals.
Key features: elements like post template tags and the get_template_part() function
that will hugely improve and streamline your work with themes.
Best practices: basic do’s and don’t’s that will help you make the right decision for
themes you build or modify.
Let’s get started!
The Four Languages You Must Know to Understand WordPress Themes
WP Shout Page 3 of 39
The Four Languages You Must
Know to Understand WordPress
Themes
To be able to make WordPress themes, you’ll need to main areas of knowledge: languages and
concepts.
The first, and our topic in this chapter, is more general: you must understand the basic
“languages” involved in making a theme. These are:
1. HTML
2. CSS
3. PHP
4. (Somewhat optional) JavaScript
If you don’t have a basic understanding of what each of those are and how they work, you’ll
spend a lot of time spinning your wheels. So let’s dive into them.
HTML, Huh? I’ve Heard of That!
HTML is the one universal part of the “world wide web”.
Though it has variants and versions, every page you see
on the internet with content inside of it is marked up
with HTML. There are no exceptions to this. Some pages
will have essentially no content inside the HTML, which
could only be there to load up some JavaScript, but with
scant exceptions if you’re seeing it in a web browser
there are some HTML tags on it. And if there aren’t
HTML tags on it, they’re interpolated by the browser so
it can make sense of the unmarked up content.
HTML isn’t really a “programming” language, it’s a “markup” language—as you probably know, it
stands for HyperText Markup Language. What this means is that it’s essentially just a big text
The Four Languages You Must Know to Understand WordPress Themes
WP Shout Page 4 of 39
document, but with “markup” baked into it to explain the specific meaning of the various bits of
text. Here’s a bit of HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Page Title</title>
</head>
<body>
<h1>Title of Page</h1>
<p class="lorem">Lorem ipsum dolor sit amet…</p>
</body>
</html>
This is a full, but very small, HTML page. The big thing to know is that most elements are
contained between two different tags, which are themselves bound by less-than and greater-
than signs. Some elements are self-closing (<meta charset… /> in this example), and
elements can be given attributes, like the class of lorem defined on the <p>, or paragraph,
element.
CSS: Making HTML Look Good
CSS, which stands for Cascading Style Sheets, is the way
that (almost all modern) webpages are given a specific
appearance. In CSS you’ll style either HTML elements,
like an <h1> or a class, like the lorem we called out
earlier. In either case the syntax is pretty uniform, and
looks like this:
.lorem {
font-family: 'Libre Baskerville', sans-serif;
}
The big thing to notice here is that we’re declaring rules, plus the HTML element (or
elements) that the set of rules affects. In this case, we first decide that the rule applies only to
those elements given the lorem class. Then, inside the curly braces, we declare the property—
font-family, meaning which font to use—followed by a colon. Then we declare the value of
The Four Languages You Must Know to Understand WordPress Themes
WP Shout Page 5 of 39
that property: “Libre Baskerville” or, failing that, the default sans-serif fallback font. We follow
the whole declaration by a semicolon. New lines after the semicolons are common but not
necessary.
The hard part about CSS is to know which properties to use to give your page the appearance
you want. Whole books are written about that topic, so we’ll move on.
PHP: The Engine of WordPress
PHP is what runs WordPress on your web server.
Whether your site is on WordPress.com or is a self-
hosted WordPress.org site, it’s using PHP on the
server to build your pages and put them together.
Therefore, PHP is (arguably) the most important
language for truly understanding WordPress. All
the core concepts we’ll be talking about with respect
to WordPress themes take place within the context of
PHP running on the web server.
PHP was initially built with the intent of allowing more intelligent creation of HTML pages. It’s a
hypertext preprocessor, meaning a language that generates or modifies HTML directly on the
server, before it gets sent to your browser. This is the “HP” in “PHP.” (Believe it or not, the first
“P” stands for “PHP” itself, making the full acronym PHP: Hypertext Preprocessor. This is what
nerds call a “recursive acronym,” on those rare occasions when anyone will talk to them.)
So when a visitor requests a page on your site, PHP creates the page right on your web server
(the place where your site is hosted). Once PHP has done its work, the server will send the
generated HTML markup to the visitor’s browser, which then displays it.
For WordPress themes, the basic logic and structures of PHP are what’s really important. Here’s
a snippet, which we’ll then explain.
The Four Languages You Must Know to Understand WordPress Themes
WP Shout Page 6 of 39
<?php
$variable = 4;
$math = $variable + 1;
if ($math > $variable) {
echo "Yay. Math yielded $math! ";
echo 'Variable was '.$variable.'.';
}
?>
<p>I'm an HTML paragraph. Hi!</p>
<?php if (true) : ?>
<p>I'm HTML that will render.</p>
<?php endif; ?>
<?php if (false) : ?>
<p>I'm HTML that won't render.</p>
<?php endif; ?>
There are a few important things to know about this. First, anything that’s not within PHP tags
(<?php and ?>) is just going to come out to the visitor as ordinary HTML when that file is
received from the server.
Also, variables in PHP start with a dollar sign, and you do math with them just about like you do
in algebra class.
Within a block of PHP, you use the echo commend to render things out the final page.
The final big thing that our example points out is that HTML which is surrounded by PHP logic is
controlled by it—this is why the HTML inside the first PHP conditional will show up on the page,
but the second won’t.
There’s loads more to understand about PHP, but this is a start.
The Four Languages You Must Know to Understand WordPress Themes
WP Shout Page 7 of 39
JavaScript: Let’s Program Web Browsers
JavaScript (no acronym, thankfully) is a flexible
programming language whose main use in a
WordPress context is to control the behavior of
HTML pages after they’ve hit the visitor’s web
browser. So if you click a button somewhere on a site,
and the background color of the site fades from red to
blue, that’s most likely (a weird use of) JavaScript.
JavaScript has seen a big resurgence in the last half
decade, primarily because client-side scripting
(another way of saying “code that executes in the browser and can interact with the user in real
time”) can be so valuable: it allows for much quicker interactions and a sense that the page is
really working for you, the user. This is the purpose for which JavaScript was invented, and still
its most common use case—though people are starting to use it everywhere else, too.
A WordPress theme can work perfectly and run very well without using JavaScript at all; but, like
much of the web, JavaScript is seeing more and more use inside both WordPress themes and
the core of WordPress itself. However, we’ve already gone on quite long about the other
languages, so I’ll skip the examples of JavaScript entirely for now.
Now You Know
Obviously we’ve barely scratched the surface of how these four languages work, and how you
can use them effectively in WordPress themes. But I hope we’ve armed with you just enough
knowledge to feel prepared to change the colors on your site with CSS, change your header
markup with HTML, or start to modify the logic of your theme templates with PHP. Just knowing
these four languages and how they differ is a great place to begin to understand and work with
WordPress themes.
The Three Core Concepts of WordPress Themes
WP Shout Page 8 of 39
The Three Core Concepts of
WordPress Themes
To really comprehend what WordPress themes are doing, you’ll need to understand three
primary core concepts:
1. The template hierarchy
2. “The Loop”
3. The basic dynamics of hooks
If you understand these three things, you’ll then be able to manage and quickly learn the
specific syntax and necessary functions for making a WordPress theme.
First, though, we’re going to start with a metaphor that will clarify and contextualize the whole
discussion.
WordPress is a Factory for Processing Posts into Webpages
I think the easiest way to understand these
three key concepts is by analogy. So I came
up with one I like pretty well: WordPress is a
factory that makes webpages. More
specifically, it processes one or more
WordPress posts stored in your database
into the webpage your browser sees.
Any request to your server—for your author page, or that blog post you wrote a month ago, or
for the search results for the term “WordPress theme,” whatever—hits the WordPress factory
and requests what it wants right at the factory’s order window.
This then sets off a bunch of procedures that are important but beyond the scope of this article,
which end with a payload of posts coming back from the factory’s warehouse (the database)
with the post or posts that we requested at the window ready to be made into a webpage.
The Three Core Concepts of WordPress Themes
WP Shout Page 9 of 39
One Factory, Many Assembly Lines: The Template Hierarchy
So a bundle of posts, all ready to be
processed, just rolled up to the back
door of the factory. But the factory
(through your theme) provides a lot
of possible assembly lines to send it
down. It’s important for the proper
functioning of the factory that there’s
always a line that can take the bundle
of posts. This is why every WordPress
theme must have
an index.php template file.
But WordPress also makes it really
easy for you to divert certain bundles
of posts down different lines. This is what the template hierarchy does: it decides which
assembly line (which WordPress template file) should process a given bundle of posts.
All lines do their work through the same basic means, called “The Loop”—so every line should
theoretically be built to handle any bundle. What the template hierarchy does, though, is make it
easy to change which line handles a particular page. For example, you can create a custom
template for your author page, with elements unique to that page, by creating a file in your
theme called author.php.
Processing the Posts: The Loop
As we said, all valid assembly lines in the factory will process the bundle of posts through the
same basic method, called “The Loop.”
Before I understood The Loop, I’d hear people mention it and think that it must be some
complex topic that I couldn’t begin to understand. It’s actually almost exactly the opposite: The
Loop is a super-simple concept. It’s just sometimes hard for beginners to recognize it among all
other PHP that’s going on in a given page template.
We’re going to bring you up to speed in the next chapter, “Demystifying ‘The Loop’ in
WordPress,” but for now let’s just check out the essentials, in these few lines of PHP:
The Three Core Concepts of WordPress Themes
WP Shout Page 10 of 39
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
// Post content here
endwhile;
endif;
This asks of the bundle, “Do you have posts in you?” If the bundle says yes, it then says “As long
as you have posts, queue each one up and run this process for me.” (It’s the combination
of while ( have_posts() ) : and the_post(); which does this.)
Then we’re going to run some process one each post. The process is missing in the example
above—it’d go where // Post content here currently sits. The process determines how your
posts will be displayed in WordPress. This is also where the “Post tags” you may recognize—
the_title(), the_permalink(), are used. You’ll sometimes see these farmed out to a
separate file, in which case you’ll typically see get_template_part() (more on that in a couple
of chapters) used inside “The Loop,” rather than the template post tags. In either case, The Loop
is just a simple way of WordPress running through all the posts which have been fetched
from the database, and processing them into a webpage to appear in the user’s browser.
Factory Workers: Filters and Action Hooks
One thing we’ve left out of this discussion, so far, is
how plugins and your theme’s functions.php file
(which is essentially “your theme’s plugin”) can have
any effect on the factory’s processes. The method is
called a “hook”—and I actually think it’s useful to think
of them as literal hooks.
What I mean by literal hooks is this: the factory (the core code of WordPress), must be kept
immaculate so that the factory’s overlords (the people who make WordPress’s core code) can
reconfigure and expand the factory (release new versions of WordPress) when necessary. So the
plugins and functions from your theme can’t stay inside the factory. They’ve got to wait outside.
Factory workers, knowing the value of these outside contractors, have to go fetch anyone who
has requested to work with them on their task. So the outside contractors leave a note on a
hook in the factory lobby for the workers to come get them, and the workers always check that
hook as part of their work process.
The Three Core Concepts of WordPress Themes
WP Shout Page 11 of 39
What that actually looks like is:
function new_excerpt_length($length) {
return 200;
}
add_filter('excerpt_length', 'new_excerpt_length');
Essentially, the add_filter is our contractor new_excerpt_length leaving a note for
the excerpt_length worker inside the factory. The excerpt_length worker goes and gets
the new_excerpt_length contractor, who, in this case, takes the $length value the
excerpt_length worker hands him, and always hands back 200. excerpt_length takes that
200, and does with it what he was originally going to do with $length. (new_excerpt_length
is not necessarily the most inspiring independent contractor. Maybe he’s some sort of purist.)
There are many other nuances about this, which we cover in a separate post called “A Simple
Way to Understand WordPress Hooks.” Have a look!
Wrapping Up
We could obviously flesh out this analogy a lot more, and there are a ton of details that we’re
glossing over. But hopefully you now feel like you have a basic understanding of the dynamic of
how WordPress works with your theme to render the pages that are its product.
Demystifying “The Loop” in WordPress
WP Shout Page 12 of 39
Demystifying “The Loop” in
WordPress
One of the first things that typically stumps people trying to make WordPress themes is the
concept of “The Loop.” It’s the core concept of WordPress, so wrapping your head around it is
definitely worth the upfront time cost. Our goal here is to make the concept clear first, and then
to move on and show you how the code works.
“The Loop” in Plain English
In this section, I promise, no programming. We’ll just go over basic concepts.
The main building blocks of of WordPress are “posts.” The terminology here gets a bit confusing,
because WordPress by default has multiple post types, one of which is called “Posts,” and the
other called “Pages.” For the rest of this piece, I’m going to use “posts” in the WordPress sense:
“a long block of HTML saved in a database.” This includes Posts, Pages, and any other post type
you can dream up.1
WordPress is built around the idea that you’re writing and storing posts (just one last time:
“Pages” are also posts) and it’s going to display your posts to the world on your website. This is
where The Loop comes in. The WordPress Loop is the method WordPress uses to display
posts.
Inside “The Loop,” you specify how you want those posts to be laid out. WordPress will reuse the
format you specify for all the posts it’s going to display on a given webpage. If there’s only one
post on the webpage—which is what we get when someone clicks onto a section of your site
containing either a page or just a single blog post—WordPress will still use the core concept of
The Loop to process the (single) post into what you see when the webpage loads.
1 As a last, hopefully unnecessary, language note: a “webpage” is not the same thing as a WordPress post. Rather, a
webpage is a complete package of HTML content—header, footer, sidebar, post content, everything—sent to and
rendered by your web browser. The Google homepage is a webpage, as is the homepage of your WordPress site.
Read the rest of this chapter and then come back to the following statement: “’The Loop’ processes WordPress
posts in order to display them to users as webpages.” It should make sense.
Demystifying “The Loop” in WordPress
WP Shout Page 13 of 39
The use of The Loop is more obvious on your homepage, or your main blog page, where
WordPress cycle through, say, ten blog posts, reusing the format we’ve specified. The WordPress
Loop is an “iterator”—programming jargon for something that repeatedly does something.
Specifically, The Loop iterates over all the posts brought back from the database. No matter
how many posts there are going to be—1 or 100—you’ll always put the basic skeleton of the
iterator in place, and WordPress will repeat it across all the relevant posts.
The Minimal Loop
<?php if ( have_posts() ) { while ( have_posts() ) { the_post(); // // Post content here // } // end while } // end if
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // // Post Content here // endwhile; endif;
Two examples at once? Have I gone crazy?! No. I list them side by side because both examples
above are identical in functionality, they just use different symbols to communicate it. You’ll see
both formats frequently as you poke around WordPress themes, so I’ve included them both.
Essentially, both if () {} and if () : endif; are ways we program conditions. Like many
languages, PHP supports different syntaxes to specify conditional behavior. In the left example
we’re saying, “If the condition inside the parenthesis is true, do what’s between the curly
brackets.” In the right case, we’re saying “If the condition in the parentheses is true, do what
comes after the colon and before we tell you to stop with endif.”
From the top—computers read just like we do—the first question of The Loop is a simple one:
“Are there posts to display?” If there aren’t, WordPress will move on and ignore the rest of The
Loop (jumping past the } or endif;). If there are, then we proceed onward, where we
encounter while. A while and an if have a lot of common, so if you understood the last
paragraph you’re most of the way there.
The difference about while is that unlike an if, which asks its question once and then
continues on, while continues to do what’s between the curly braces (or, in the example on the
right, between :and endwhile) until its condition stops being true. What that means, in English,
is that now that WordPress knows it has at least one post(s), it will keep “iterating” the stuff in
the while loop until it’s out of posts.
Demystifying “The Loop” in WordPress
WP Shout Page 14 of 39
OK, one last issue: the stuff inside the while loop. There’s not much there in our example,
because we’re keeping it light and only one thing must be in your while loop. That’s
the the_post() “function call.” A stack of posts has come into the page, was verified to exist by
the if, and verified to have stuff in it by the while. Now, the_post() is the worker who takes
each post in that stack, one by one, and makes it ready to use.
In our giant factory, the_post() is the truck-unloader who pulls one giant chunk of raw steel
out so that we can start to fashion it into our giant gear. Because he’s only called once, he just
unloads one piece, makes it ready for work, and sends the truck back around to the while loop.
If the while inspector finds something more to work on in the truck, she’ll send the truck back
around and the_posts() will take off another piece. If not, the truck will continue on and exit
“The Loop.” This cycle will always continue until the truck is empty.
An Example of The Loop in Action
My hope is, after reading the functioning of the The Loop in programming-jargon-less terms,
and then with the minimal programing jargon, you’ll be able to understand a real-world
example. This example might be found in a very basic theme’s index.php file.
<?php if (have_posts()) { ?> <?php while (have_posts()) : the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; } ?>
One of the first things to realize about above example is that in the above section, everything we
had was PHP, but now we’re putting some HTML right along with it. Things that are
between <?php and ?> are considered valid PHP logic when run on the server; things that aren’t
are just controlled by the surrounding PHP logic. That is: If the PHP that surrounds our HTML
says the HTML should show up on the final page, it will. If it doesn’t, it won’t.
Now a few things about the example are a bit weird. First, for learning’s sake, I’ve declared
my if condition with curly braces and my while condition with a colon and an endwhile. This
will function perfectly, it’s just a bit confusing to the reader, so best not to do it in real life.
Similarly, in the last section we had the_post() on its own line and here it’s sharing the line
with the existing while condition. Again, this is totally functional PHP and will work without
problem. It’s just an example of the ways in which real-world uses of The Loop may vary.
Demystifying “The Loop” in WordPress
WP Shout Page 15 of 39
The truly new stuff though, is that middle line, the one that starts <li>. The HTML
tags <li></li> surround “list items,” just as <a></a> surrounds a link.
Essentially, in WordPress, you use functions like the_permalink() and the_title() to get
data about the current post. These functions are called template tags (check out our later
chapter on them!), and they just output the data that they describe right into the HTML that
surrounds them. So once filled in by The Loop, each post that is being iterated over in this loop
would spit out something like:
<li><a href="http://pressupinc.com/blog/2013/07/demystifying-the-loop-in-wordpress/">Demystifying "The Loop" in WordPress</a></li>
This is a list (<li></li>) containing a link (<a></a>) that points to the post
using the_permalink(), and displays the_title(). Many other WordPress template tags do
exist, like the_content(), which displays the contents of the post, and the_excerpt(), which
displays either the first part of the post, or the excerpt that is manually set for the entry.
Onward to New Heights
There are no doubt details about the The Loop I failed to explain sufficiently. But I hope I gave
you a good simple overview of the how the whole thing works to transform posts into
webpages. Understanding The Loop is one of the most powerful pieces in starting to
understand how WordPress works.
Understanding the WordPress Template Hierarchy
WP Shout Page 16 of 39
Understanding the WordPress
Template Hierarchy
One of the simpler and more powerful concepts that runs underneath WordPress themes is the
template hierarchy. It’s super powerful and can make your life much easier as you build out a
theme for your site. And it’s not all that complex, so once you get the idea you’ll find working on
themes much easier.
The Problem that Leads to the Hierarchy
WordPress wants its themes to be two things: easy to customize and hard to break. When
themes do end up having both these qualities, it’s part of what makes WordPress great—but
balancing them is something that takes some thought and insight.
To make themes hard to break, WordPress can always render pages by falling back to
index.php and The Loop. This has two parts: use of The Loop, and the existence of
index.php as a fallback.
First, every template file uses The Loop. There’s no such thing as a “page Loop” and a “blog post
Loop” and an “author page Loop.” It’s all one thing, and this abstraction makes WordPress much
better able to guarantee that any given template file can render any given content.
Second, every page can always fall back to index.php in the absence of more specific template
files. Every WordPress theme needs an index.php file, and index.php should be running The
Loop. This allows WordPress to use index.php anytime it doesn’t have a better-fitting file to
render a particular page.
Put together these two elements makes a WordPress theme hard to break: even for obscure
new content types, WordPress will always be able to fall back to index.php and The Loop to
catch and render them.
To make WordPress easy to customize, WordPress has built up a large choice tree of
additional template options on top of index.php. WordPress can always count
on index.php being there: but it’ll try to find a better, more specific template file to use if one
exists. For example, I want to change the page layout for when visitors are just viewing a single
Understanding the WordPress Template Hierarchy
WP Shout Page 17 of 39
post, I can make a file called single.php, with The Loop inside of it, and WordPress will use
that when it thinks there’s only one post on the page. This is powerful.
The Dynamics of the Template Hierarchy
As we’ve said, WordPress has built up some really powerful choice trees.
Let’s say you want to customize the way your category archive—the listing of multiple posts
from a single category—will look. If you’ve got an index.php in place, the first option you have
is to create or modify archive.php. This is the template that WordPress uses for any archive,
so you could customize that if you also want your customizations to apply when your visitor
clicks onto archives based around tags, or the month of publication.
If you don’t like that, we can then continue down the path: the next option is that we can create
or modify category.php. This will be used for any category archive, but only for category
archives—not archives by date, tag, author, etc.
Understanding the WordPress Template Hierarchy
WP Shout Page 18 of 39
But if you now decide that you only want your changes to apply to one category archive—for
example, “Poems”—you’ve got a few more options. You can create a new template file called
category-poems.php or, if you figure out the category number, category-32.php, and
WordPress will use that to render the view when someone click a link to the post category
whose category slug is poems (which, if you’ve done it right, should correspond to your “Poems”
or “Poetry” post category).
As simple as this dynamic is, you may be able to imagine its considerable power. One thing it
implies is that customization and improvements can be made on the fly as you build out a
WordPress theme. start with a simple index.php, get it set up just how you like, and then
tweak it for all the different ways that WordPress will possibly find itself displaying your content.
Seeing the Whole Hierarchy
Once you understand the core concepts above, the next step is just to learn the various ways of
stacking WordPress templates and creating new ones.
Listing out the specific layout of each tree that WordPress looks at for each type isn’t all that
useful here, so I’ll refrain. I promise it’d only bore both of us. But there are a few exemplary ways
to see and understand this data when you need to reference it:
Template Hierarchy on the WordPress Codex: The Codex is the canonical source for all
your information about WordPress. Learn to love it. The page is quite long and detailed,
which makes for somewhat dull reading, but makes it super valuable as a reference. You
can easily CMD/CTRL+F for whatever you specific problem is—“single taxonomy” for
example—and quickly find a great explanation.
WPTuts+ Cheat Sheet: Especially if you understand the basic terminology and function of
WordPress functions like is_home(), I really appreciate the brevity of this visual map. It’s
not exhaustive, but it’s easy to read. (It’s also the image in the previous section.)
Marktime Media’s Graphical Version: These are a bit large and unwieldy for many
contexts, but they’re really thorough and rather nice-looking to boot. If you’re a real
WordPress nerd you could even use them as your desktop background.
Onward!
Make Your Themes Better By Getting to Know get_template_part()
WP Shout Page 19 of 39
Make Your Themes Better By
Getting to Know
get_template_part()
One of the easiest mistakes to make when you first start to make WordPress themes is
duplicating code. In fact, avoiding duplication is both one of the simplest and most complicated
lessons of making good software anywhere.
Duplicating code with a quick copy-and-paste is super easy, and in the short term you feel really
efficient—look at all these things I’ve accomplished quickly! But beware: That way madness lies.
Why Duplication is the Enemy of Maintainability
As time passes, you start to find that the code you quickly copied needs to change. And then
you’re faced with an ugly choice: you either have to manually find and replace the code
everywhere you’ve pasted it, or cross your fingers and pray you can get away with only changing
the instances you notice.
As most people probably do, I learned to work in WordPress by duplicating and then modifying
an existing WordPress theme. I was hugely efficient at first: I had a working theme almost
instantly. But then I’d decide that I wanted to change something about how post metadata
looked—say, flip the calls to the_category() and the_date()—and I’d have to go modify it in
every file in the template hierarchy.
Anyway, I was doing this in the bad old days before WordPress had child themes, or cool tools
like get_template_part(), and so I suffered through the downsides of duplication. Let my
hard-won lesson be your gain: use get_template_part() for any code you’re thinking of
copying and pasting in your theme.
How do you do that? I’m glad you asked.
Make Your Themes Better By Getting to Know get_template_part()
WP Shout Page 20 of 39
What is get_template_part?
Put quite simply, get_template_part() is a
WordPress function that includes template “partials”
wherever you need them. The canonical example is,
as I mentioned above, when you have a particular way
you want your posts displayed across many files.
index.php, search.php, and archive.php are
obvious places where you might be looking to use an
“abbreviated” post format which you want to look
consistent.
What you should do, then, is put your abbreviated
post layout in a file—we’ll call it abbreviated.php—and then use get_template_part() to
pull it in anywhere you want to use it.
In other words, get_template_part() is a way for you to abstract repeatable pieces of
your WordPress templates into their own PHP files. This bits of code are the “template parts”
themselves. You write each “template part” once, and use it across as many template files as you
want. And when you’d like to change something around, you only have to change one file.
For clarity’s sake, here’s an example use of get_template_part() in an index.php file:
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'abbreviated' );
endwhile;
endif;
And here’s the actual content of our theoretical abbreviated.php:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title( '<h2 class="entry-title"><a href="' . esc_url(
get_permalink() ) . '" rel="bookmark">', '</a></h2>' ); ?>
<?php the_excerpt(); ?>
</article>
Make Your Themes Better By Getting to Know get_template_part()
WP Shout Page 21 of 39
Now the clever among you may have an interesting but dangerous thought: “Why not just use
PHP’s include or require functions?”
Well, you can, and it’ll work. But if you ever want to make a child theme that inherits from your
theme, or want to use a better bit of get_template_part() we’ll cover below, you may have
issues. get_template_part() makes it easy for a child theme to just replace your
abbreviated.php file, but if you include things instead, the child theme will be forced to
replace every file in which you used the include. So while it works, I’d recommend against it.
Another Perk of Using get_template_part
You can use a second parameter on get_template_part,
which makes it even more powerful. If you care at all about
post formats, this feature is for you. The Codex actually
explains this bit really well, so I may as well just quote it:
Assuming the theme folder is wp-content/themes, that
the parent theme is twentyten, and the child theme is
twentytenchild, then the following code –
<?php get_template_part( 'loop', 'index' ); ?>
will do a PHP require() for the first file that exists among
these, in this priority:
1. wp-content/themes/twentytenchild/loop-index.php
2. wp-content/themes/twentyten/loop-index.php
3. wp-content/themes/twentytenchild/loop.php
4. wp-content/themes/twentyten/loop.php
What does that have to do with post formats? Well, if your second parameter is your post’s
format, get_template_part() can locate the “template part” that gives special rendering for
that format, if it exists, or else fall back to the default you’ve set. In most default WordPress
themes, and many others, you’ll see this come out like this:
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
Make Your Themes Better By Getting to Know get_template_part()
WP Shout Page 22 of 39
At first glance, this may just look confusing. But all it’s doing is safely handling any post format
anyone ever dreams up. Most of the default themes have robust and specific support for all the
post formats, but if you’re just dipping your toe in you can create the ones you know you want
and skip the rest. The magic of get_template_part() will make sure your setup always works.
In Conclusion
get_template_part() is a powerful and valuable part of WordPress. You’ll see it in most good
themes you try to edit, and now I hope you know what it’s doing and why it’s valuable.
I want to close by mentioning one issue I’ve hit my head against: because of the way
get_template_part() works, your local variables in the parent file aren’t accessible in
the included file. (Examples of these variables: a rudimentary counter in your instance of The
Loop, or a more complex determiner of some state you want to add to your post class.)
To fix this, you could make your local variables global, redesign the concept that requires them,
or do a different weird dance. However, there’s another option:
the locate_template() function that get_template_part() uses under the hood. You can
run a quick include(locate_template('your-template-name.php')); For more on this,
read from Keith Devon.
Happy theming!
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care
WP Shout Page 23 of 39
WordPress Post Template Tags:
What They Are, How You Use Them,
and Why You Care
Template tags are such a core concept in WordPress that most people who’ve ever used PHP in
the vicinity of WordPress have used them in some capacity. the_title() is a common
template tag, and it belongs to the special class we’re talking about here. But things
like get_header(), wp_dropdown_users(), and way more others than I can count, are also
classified as Template Tags in the Codex.
On this subject, I think the term “template tags” suffers from an overabundance of meaning:
there are so many types of “template tags” that it’s hard to say meaningful things about them as
a class, except that you use them in templates or themes in WordPress. So for that and a few
other reasons, I’m going to limit this discussion to the “Post tags,” and, in fact, only the small
class of functions like the_title() that are most commonly used.
The Loop and Post Template Tags
So the most important, and probably the first, template tags
you’ll understand are the ones that display specific parts of
your “post”—things like the_title(). As you can probably
guess, the_title() shows the title of your post.
And the_content()? Yeah, it displays the body or “content”
of your post. the_tags() shows the tags that your post is
marked with.
All the examples I’ve listed, and most of the rest of those that
the Codex labels “Post tags,” only make sense and should
only be used inside of the The Loop.
What happens if you try to use an inside-The-Loop template tag outside of it? Your results may
vary, but the default is that you’ll get the result for only the first post that The Loop would have
queued up.
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care
WP Shout Page 24 of 39
Using the_title() and get_the_title(): What’s the
Difference?
We’re going to delve into the_title(), and its partner, get_the_title(), first and foremost,
to make the point that most of these loop or post template tags are paired like this. This is
something it took me far too long to learn as a PHP and WordPress novice. Here’s the rule:
Want to show something? Use a template tag with the_ on the front,
like the_title().
Want to manipulate a value before it’s shown? Add a get_ to the front of the
template tag, like get_the_title()—and don’t forget to echo the result.
Just to make the point literally, here is how you can display the titles of your posts:
<?php the_title() // Outputs "My Awesome Title"
To display the titles of your posts, but only after removing the first ten characters—which you
would do because you have gone mad—you’d do something like:
<?php echo substr(get_the_title(), 10); // Outputs " Title"
This basic pairing of the_ and get_the_ is pretty common in WordPress and a nice idiom. If
you see something like “echo get_the_title(),” you know you can just chop it down
to the_title().
Diving Into Core: Understanding a Bit Deeper
While “hacking core”—changing the actual contents in the files—is hardly worth recommending,
looking at it and being familiar with it is an invaluable thing to do. So I’ve gone in and pulled out
the source for the two functions we discussed above. We’ll start with the_title:
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care
WP Shout Page 25 of 39
function the_title($before = '', $after = '', $echo = true) {
$title = get_the_title();
if ( strlen($title) == 0 )
return;
$title = $before . $title . $after;
if ( $echo )
echo $title;
else
return $title;
}
This code is just a thin wrapper for get_the_title(). Cut out the dealing with all the weird
and rarely-used parameters that it turns out the_title() accepts, and you’ve basically
got echo get_the_title(). Cool.
So let’s take a gander at get_the_title():
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care
WP Shout Page 26 of 39
function get_the_title( $post = 0 ) {
$post = get_post( $post );
$title = isset( $post->post_title ) ? $post->post_title : '';
$id = isset( $post->ID ) ? $post->ID : 0;
if ( ! is_admin() ) {
if ( ! empty( $post->post_password ) ) {
$protected_title_format = apply_filters( 'protected_title_format',
__( 'Protected: %s' ) );
$title = sprintf( $protected_title_format, $title );
} else if ( isset( $post->post_status ) && 'private' == $post-
>post_status ) {
$private_title_format = apply_filters( 'private_title_format', __(
'Private: %s' ) );
$title = sprintf( $private_title_format, $title );
}
}
return apply_filters( 'the_title', $title, $id );
}
There’s a bit more here, but a quick look reveals some interesting insights. The most important
is that our post titles get quite a layer of protection outside of the admin area: visitors are
explicitly blocked from seeing the title of a post which is Protected or Private.
Outside of that block, though, we’re not doing a lot here. Essentially, we get the post—diving
into get_post is an interesting idea, but for now we’ll just know that it gets the right post based
on various fiddling and generally the global $post variable—and then pulls from that
$post object some local variables which are used when the the_title filter is applied.
Closing Up
Hopefully you know more than you did when you started down this page, in particular about the
subclass of Template tags that we refer to as Post tags, what they do, and how you can easily
manipulate their values by tacking the a get_ on the front.
How to Link to Your WordPress Theme Resources
WP Shout Page 27 of 39
How to Link to Your WordPress
Theme Resources
WordPress theme developers frequently need to link to resources elsewhere in the site’s
directory structure, like images or JavaScript files. This is easy, but it requires a little learning,
because the regular ways you’d do it outside WordPress won’t work very well.
What Not to Do
First off, because of the way WordPress renders pages and makes pretty URLs, you can’t use
relative links (links that exclude the web address, like simply “about” or “/about”). Trying this
will simply result in a broken link.
Your next thought may be to link to the absolute URL of the file, like
“http://www.mysite.com/wp-content/themes/mytheme/images/my-image.png.” This is
functional, but it’s got a huge problem: if anyone ever installs your theme on any other domain,
they’ll pull the resources from your server, not from their own. Never mind.
So now you look around a bit and find get_theme_root_uri(). “Huzzah!” you shout. Cracked
it! So you go ahead and link to your image like so:
<img src="<?php echo get_theme_root_uri(); ?>/mytheme/images/photo.jpg">
It works! And it’ll continue to work, until someone decides to modify your theme and changes
the name of the folder the theme is in from “mytheme” to “actually_this_is_mine_now.”
Then everything breaks.
How to Link to Your WordPress Theme Resources
WP Shout Page 28 of 39
The Right Ways to Link to Theme Resources
Fortunately, WordPress has functions to do this properly. My favorite is
get_stylesheet_directory_uri(), which returns the absolute URL correct for the
specific current WordPress environment and running theme. This one will work
flawlessly, even if you’re currently working on a child theme.
<!-- relative to current theme, even if child --> <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/photo.jpg"> <!-- relative to current theme when it's not a child --> <img src="<?php echo get_template_directory_uri(); ?>/images/photo.jpg">
There is a common alternative: get_template_directory_url(), which you can use as long
as your theme is the primary one (either the parent theme or the only theme). But for child
themes, get_template_directory_url() will link you relative to the parent theme, not
your own theme. This one is good to have in your back pocket, though, because sometime you
may want to link to resources in a parent theme.
A Function to Make Linking to Resources Even Easier
Now, if you’re not a finicky perfectionist, you may want to stop now. What’s below is some
syntactical niceties that make me happier when linking to my theme’s images or JavaScript files.
They probably entail a very modest performance hit, but I think their increased legibility justifies
that. The following simple functions are typically the very first things I put in my theme’s
functions.php file:
function get_theme_uri($add_path = '') { return get_stylesheet_directory_uri().$add_path; } function theme_uri($add_path = '') { echo get_stylesheet_directory_uri().$add_path; } // Only include these if you link to your theme's parent files function get_parent_theme_uri($add_path = '') { return get_template_directory_uri().$add_path; } function parent_theme_uri($add_path = '') { echo get_template_directory_uri().$add_path; }
How to Link to Your WordPress Theme Resources
WP Shout Page 29 of 39
There are few obvious notes about these functions:
They are incredibly short.
And don’t do much.
But they do allow you to pass in the path of the file relative to your theme root as a
function argument.
Following the basic pattern of WordPress core functions, I’ve made
a theme_uri() function which does the same thing as the get_theme_uri() function,
but echos it so I don’t have to do a <?php echo function(); ?> which I always find a
little ugly.
So it allows us to do this:
<img src="<?php theme_uri('images/picture.jpg'); ?>">
This just looks so much better to me than any other alternative that I almost always make these
functions available to myself.
In Conclusion
We’ve covered a lot of wrong ways and a few right ones. If you’ve read carefully, you should
never have trouble linking to theme resources.
Four Things a WordPress Theme Shouldn’t Do
WP Shout Page 30 of 39
Four Things a WordPress Theme
Shouldn’t Do
The problem we’re going to begin to discuss today goes under the general title of theme creep.
The next chapter will discuss fighting theme creep in WordPress themes that already suffer from
them, but this chapter introduces the topic and gives broad guidelines for avoiding it altogether
in your own themes.2
An Example of Theme Creep
Let’s start with a common example: A theme includes among its features an “SEO” package
allowing you to set a custom site title, meta tags, and so on, perhaps even at the post level. A
user is shopping for themes, has heard vaguely about SEO and its importance—and sees, “Hey,
this theme has that!”
As long as the user stays on that theme, things go smoothly. But when the user decides to
switch themes, it’s a big problem. All those custom page titles, meta descriptions, and
whatever else went into the (now old) theme’s SEO features will seem to disappear. The user’s
choices are pretty bleak: do a heap of complex technical work, hire an expert to save years of
SEO data, or remake all of it from scratch. It’s a frustrating problem, and an unnecessary one.
Where Theme Creep Comes From
One of the greatest things about using WordPress is that there are so many options to solve
your problem. From the crazy-simple to crazy-complex, you can find a theme at almost any price
point and visual style. Plugins as well: simple or complex, expensive or free, anything you want.
This is largely a great thing.
The problem is, especially in the premium marketplace, non-technical people are shopping
for some pretty complex things with little or no way to evaluate the wisdom of their
decision. Our theme shopper is an example: “I know SEO is important and I need a WordPress
theme… Hey look! This theme says it has SEO. And it has boxes for me to enter my data.”
2 Thanks to Leland at Theme Labs for this post about why a theme should never register its own shortcodes, which
partly inspired our discussion of theme creep.
Four Things a WordPress Theme Shouldn’t Do
WP Shout Page 31 of 39
Compounding this problem: Sellers of themes are competing to match each other feature-
for-feature, because most people in the market for WordPress themes spend their money
on a checklist of the features they understand and know they want. Shoppers don’t have
the expertise or time to understand all the complex implications that will spin off from their
theme choice. So if one theme has loads of shortcodes to allow for easy sliders and buttons, and
registers helpful custom post types like “Portfolio” and “Contact Page,” and claims it’ll do SEO, it’ll
appeal to a lot of people.
What a WordPress Theme Should Do
When we think about what a theme should do, it’s good to keep in mind a favorite software
engineering idea: “Separation of Concerns.” It’s a powerful and useful idea that is ignored by too
many people in the WordPress ecosystem. The “MVC” (model-view-controller) pattern, old-hat to
most web programmers, is a technique that assures that nothing in you system is doing too
much. Your model is your data. You have controllers, which act on that data. And you have a
“View” which displays that data.
A good WordPress theme should act as a view—and only a view—for the data that
WordPress expects it to display. We can clarify this statement by looking at its implications for
what themes shouldn’t do.
What a WordPress Theme Shouldn’t Do
A WordPress theme shouldn’t have any effect on the administration area of the site, because a
theme generally should not provide any functionality.
As a general rule, if you switch to another theme and lose anything you care about from
the dashboard (outside of the Appearance tab), that theme is doing too much. Look for a
new one, or talk to its creators and point them to this post.
Four Specific Things a WordPress Theme Should Never Do
Given what a WordPress theme should and shouldn’t do, here are four
specific practices to avoid:
1. A theme should not register content (post) types. If a theme creates
new custom post types, like “Galleries” or “Portfolios,” users will lose
those post types when they switch themes. An expert can recover that
Four Things a WordPress Theme Shouldn’t Do
WP Shout Page 32 of 39
data by declaring that same content type in a plugin, but most regular WordPress users
can’t. Why put users through this? You could have just required a plugin to do it in the
first place.
2. A theme should create no taxonomies. Similarly, a theme may try to create a new tag-
or category-like system, either for posts or pages or for a custom post type it registers.
(Which it shouldn’t have done anyway; see #1.) Again, while this data isn’t lost eternally—
an expert can recover it with some speed—it’s an unnecessary thing for a theme to be
doing.
3. A theme should not store data, or provide easy interface for some custom type of
data store. This is the SEO example I started with, if a theme stores SEO data in some
custom data structure that its creator has made up, the moment the theme goes away
the data is also lost. And unlike the last two, this is likely to be even more obscure to
recover, as even an expert would have to spend some significant time guessing the exact
data structure the theme used.
4. Finally, and this is Leland’s point: a theme shouldn’t provide shortcodes, or any other
specific means of adding unique-to-the-theme elements to post content. There’s no
inherent data-loss in this, but it does definitely break my site that where I used to have a
pretty button that did something, and now visitors see “[pretty_button
action="engages_button" label="Click my pretty button"]“. Again, this is a
fixable problem: a custom plugin for those shortcodes will get the job done. But again,
there’s no reason that the theme should have done the job in the first place.
“But, But…”
Some will argue, reasonably, that WordPress themes today need to do much more than the
default accounts for. You wouldn’t have a lot of luck selling your dog toys in a blog-type layout.
It’s true: we’re asking WordPress to do many things beyond what the first creators of themes
envisioned. But it doesn’t follow that we need themes to both display and provide this
functionality. Far better that a theme depend on well-known and established plugins to handle
the creation of maintenance of data, and limit their job to displaying that data.
If you’re making an ecommerce theme that needs a way to list products, make your theme
require WooCommerce, or your favorite ecommerce plugin. Heck, make your own ecommerce
plugin. We have tools—admittedly not as well-known, well-supported, or integrated into the
core of WordPress as they should be (Brian Krogsgard’s post about this problem is highly
recommended)—that let a theme declare its dependency on plugins. But don’t put any of the
Four Things a WordPress Theme Shouldn’t Do
WP Shout Page 33 of 39
user’s data into your theme unless you’re trying to lock them into you forever. While that may be
a business strategy, it’s not a very good one.)
How to Build Robustly with WordPress
As I mentioned above, the key to robust systems is modularity: decrease as much as
possible the irreplaceability of any component. Every component should be able to be
swapped out for another one that does the same job, and the system should just keep working.
Realistically, this is beyond what’s reasonable given the way WordPress currently works and the
way its components build on each other. But even given the structural limitation of WordPress,
keeping your theme’s job to the display of content—and keeping it away from both data storage
and the creation of data structures (like post types and taxonomies)—is a great first step.
Theme swapability is crucial if you’re hoping to build a maintainable WordPress site that’ll serve
you well for years. Educated shoppers should demand it, and WordPress professionals—both
makers of commercial themes and one-off efforts for a single user—should always strive to
deliver it.
Dealing with Theme Creep
WP Shout Page 34 of 39
Dealing with Theme Creep
Theme creep is a form of technical debt. And
technical debt is a problem because it makes a
system—in this case, your website—fragile and
harder to improve. Determining that you have the problem is one of the simpler steps you can
take, so let’s start there.
Determining if You’re a Victim of Theme Creep
The easiest way to tell if theme creep is an issue on your site is to follow a simple procedure:
1. Switch from your current theme to one that you know has no creep: I’d generally
recommend one of the WordPress defaults (the Twenty __ series, the most recent of
which is Twenty Fourteen). Out of the box, these default themes are keeping to our list of
things a WordPress theme shouldn’t do.
2. Go through the both the front end and admin area of your site looking for things that are
broken or missing. Is your FAQ page gone? Do some posts have broken shortcodes in
them? Are your extra taxonomies missing? Is your SEO data suddenly invisible to Google?
Theme creep got you.
Now that you know you’ve got a problem, what do you do?
Remediating Against Theme Creep
To be clear, theme creep doesn’t have to be a
devastating problem. All it means is that
functionality your sites always need has been
combined with the appearance of your site today.
You can deal with theme creep by separating out
those concerns, and your site will be set to move into
the future. If you’re not technical, you may need a bit
of help implementing these steps, but it’s not too
hard. Here are your basic options:
Dealing with Theme Creep
WP Shout Page 35 of 39
Make an “everything plugin.” This is pretty simple if you know only the smallest bit of
PHP. Here’s how you do it: Take the entirety of your theme’s functions.php and put
it inside a new plugin. If you’ve never created a plugin before but are interested in
trying, I recommend my “Minimum Viable WordPress Plugin” post. This plugin probably
won’t be able to run side-by-side with your creepy theme—PHP will error at you—but
when you’re on a different theme, you may be able to run both the theme and the plugin
and keep everything working. If not, you’ll want to see if your theme is require()-ing
or include()-ing other files, and bring those over as well, either by pasting them into a
single plugin file, or into unique files mirroring the structure of the old theme.
A somewhat better option is to create a plugin for each type of functionality your
theme had been providing. Your custom post types should be one plugin, your site’s
shortcodes should be another, etc. This is a better idea overall—you’ll end up with a more
modular and flexible WordPress site, and you can turn pieces of functionality on and off
independently—but it does require a bit of thinking about each piece’s purpose and a real
understanding of how PHP works.
Finally, opt out from WordPress themes that are creepy. Favor vendors that enforce
strong limitations on theme functionality, and preemptively use a theme’s support to
inquire about theme creep and theme modularity. In the worst case, you’ll discover in
advance that the theme authors’ support is lackluster, or that they’re not knowledgeable
enough to understand the issues you’re asking about. In the best case, you get a future-
friendly WordPress theme with proven support that won’t weight you down in the future.
As a theme maker or coder, there is more you can do. We won’t go into it in too much detail,
but TGM Plugin Activation is a great library and highly recommended if you sell themes, and
need to provide functionality that shouldn’t be in them.
Theme creep impacts too many WordPress sites. I hope these couple of chapters have helped
you understand it, and what to do about it. Good luck!
Always Use a Child Theme!
WP Shout Page 36 of 39
Always Use a Child Theme!
One request for help we hear far too frequently in our work at Press Up is: “I pressed an update
button, and now my site doesn’t look right.” The reason is usually that people have customized
the look-and-feel of the theme running on their site, without using a child theme.
Just using the customized theme works fine for
them, for a while. But then they’ll get a notification
that the WordPress.org repository or the
(commercial) theme distributor has a new version of
the theme. They click the update button, and all
their beautiful customizations up and vanish.
Or maybe they consciously avoid updating the
theme— but then they’re open to security
vulnerabilities. While themes are typically not doing the really risky things that some plugins
might, there are still many possible security reasons to keep them up to date.
This dilemma is why you want a child theme.
What a Child Theme Is
In plain English, a child theme is a theme that declares a “parent” theme, on which it
depends and from which it gets most of its functionality. By telling WordPress that it’s a
“child” of some other theme, a child theme saves itself from having to contain all the
features and functionality of a full-fledged theme, while still being able to make its own
CSS, and even overwrite specific page templates of the parent.
If you’re modifying almost any theme, you can make just about every presentational change
you’ll want to a child theme—all while keeping yourself up-to-date, secure, and able to take
advantage of new parent theme features. So let’s do that.
How to Make a Child Theme
Essentially, you make a child theme by creating a new theme. The first step is to create a new
folder in your themes directory (wp-content/themes) and add a file to it called style.css.
The top of the file needs to contain the following lines:
Always Use a Child Theme!
WP Shout Page 37 of 39
/*
Theme Name: Twenty Thirteen Child
Theme URI: http://example.com/
Description: Child theme for the Twenty Thirteen theme
Author: Your name here
Author URI: http://example.com/about/
Template: twentythirteen
Version: 0.1.0
*/
All but one line there is standard to all WordPress themes. The exception, which is exclusive to
child themes, is Template: twentythirteen. What that says to WordPress that this theme
should be a child of Twenty Thirteen. The reason that it’s lowercase is that this needs to use the
theme “slug,” which is the name of the folder in which the parent theme is located. By default
the Twenty Thirteen theme is in a folder with that name, and so WordPress will find it there.
There’s one problem with this new theme you’ll have
made: by default it won’t look very good. This is
because WordPress looks for every file first in the
child theme, and then in the parent if it wasn’t in
the child. Because our theme now has a virtually
empty style.css file—which is the main source of
visual styling for a theme—you’ll see something drab
and broken-looking.
The solution is a single line in the CSS file:
@import url("../twentythirteen/style.css");
What this does is pull all the contents of the parent
theme’s style.css file into your child
theme’s style.css file. Now your site’s looking
identical to the way it did—but you’re running a child
theme.
Now, if you want to add some styling to
the blockquote elements, for example, you can just
add it in your child theme’s style.css. If you want to
Well, it works better. But it doesn’t
look good…
Ah. That’s better!
Always Use a Child Theme!
WP Shout Page 38 of 39
remove some template tags from your site’s single entry template, single.php, you’ll copy that
file from the parent theme into your child theme and make your changes from there. The child
theme’s single.php will replace the parent’s one-for-one across your whole site.
You can edit your theme this way to your heart’s content, and because you’re on a child theme,
you can update the parent theme without worries. Your changes—styles you’ll add
to style.css or any replacement template you use—will be safe. Pretty cool, right?
Some Things to Keep in Mind
Here are a couple of things to know as you’re using child themes:
You can’t make a child theme of a child
theme. Like Henry VIII, WordPress doesn’t have
grandchildren. This is most notable if you’re buying
child themes from a commercial vendor, Genesis
themes being the most prominent. Because the
parent-child relationship of WordPress themes
only goes one level deep, buying (and updating) a
commercial child theme puts you back to the
drawing board in terms of the problem we
described at the beginning of the chapter.
Every file in the child theme overwrites the file
of the same name in the parent,
except functions.php. If you find that you need to change a behavior in the parent
theme’s functions.php file, you unfortunately will have to be more clever than copying
over the functions.php file and making your changes. That works for every page
template, but it doesn’t work for the logical controller that is functions.php. A child
theme’s functions.php is run and processed before the parent’s—rather than
replacing it one-for-one like the other files.
Check out child themes! We love them, and we think you will too.
Summary
WP Shout Page 39 of 39
Summary
Whew! WordPress themes are simple to use, but there’s quite a bit going on under the surface.
On the other hand, the WordPress theme architecture is (mostly) elegantly and thoughtfully
designed—so it pays huge dividends to people who are curious and willing to learn.
We hope Mastering the Fundamentals of WordPress Themes has helped you navigate the world of
WordPress themes, and has helped elevate you from a simple consumer of themes to someone
who can make powerful changes within them, and even make thoughtful decisions about what
they do and how they should be structured.
If you’ve enjoyed this book, we have a few suggestions for you:
Keep learning. WordPress gets cooler the deeper into it you go—and if you’ve read and
understood this book, you’ve gotten a lot of the foundational stuff out of the way.
Say hi. At WPShout, we’d always love to hear from you. If this book has left you with a
burning question, tell us about it! We’ll try to answer, either directly or in a tutorial post.
Stay tuned. Over the next several months, we’ll be developing Mastering the Fundamentals
of WordPress Themes into a full-fledged guide for people wishing to understand the
fundamentals of WordPress development. If you’d like to be included on the release list
(and get a 25% discount when the book drops), then email us and we’ll add you right
away. And to stay updated on all our WordPress tutorials, like us on Facebook and follow
us on Twitter.
Thanks for reading, and talk to you soon!
–Fred and David from WPShout
[email protected] | facebook.com/wpshout | twitter.com/wpshout