Académique Documents
Professionnel Documents
Culture Documents
Fundamentals of
WordPress Themes
How Themes Work, and How to Make
Them Work For You
Brought to you by
Sponsored by
Introduction
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 Shouldnt Do .................................................................................. 30
Dealing with Theme Creep ................................................................................................................... 34
Always Use a Child Theme! ................................................................................................................... 36
Summary ................................................................................................................................................ 39
WP Shout
Page 1 of 39
Introduction
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 WordPresss thorough and ingenious use of themes, which can
give users a huge head start toward creating exactly the site look-and-feel theyre after.
But theres 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. Well be
lifting the hood on WordPress themesso 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.
Well 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 dos and donts that will help you make the right decision for
themes you build or modify.
WP Shout
Page 2 of 39
WP Shout
Page 3 of 39
document, but with markup baked into it to explain the specific meaning of the various bits of
text. Heres 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 greaterthan 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.
Page 4 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 well move on.
WP Shout
Page 5 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 thats 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 itthis is why the HTML inside the first PHP conditional will show up on the page,
but the second wont.
Theres loads more to understand about PHP, but this is a start.
WP Shout
Page 6 of 39
WP Shout
Page 7 of 39
WP Shout
Page 8 of 39
Page 9 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. (Its the combination
of while ( have_posts() ) : and the_post(); which does this.)
Then were going to run some process one each post. The process is missing in the example
aboveitd 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. Youll sometimes see these farmed out to a
separate file, in which case youll 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 users browser.
Page 10 of 39
Wrapping Up
We could obviously flesh out this analogy a lot more, and there are a ton of details that were
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.
WP Shout
Page 11 of 39
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 contentheader, footer, sidebar, post content, everythingsent to and
rendered by your web browser. The Google homepage is a webpage, as is the homepage of your WordPress site.
1
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.
WP Shout
Page 12 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 weve specified. The WordPress
Loop is an iteratorprogramming 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 be1 or 100youll always put the basic skeleton of the
iterator in place, and WordPress will repeat it across all the relevant posts.
<?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. Youll see
both formats frequently as you poke around WordPress themes, so Ive 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
were saying, If the condition inside the parenthesis is true, do whats between the curly
brackets. In the right case, were 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 topcomputers read just like we dothe first question of The Loop is a simple one:
Are there posts to display? If there arent, 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 youre 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 whats 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 its out of posts.
WP Shout
Page 13 of 39
OK, one last issue: the stuff inside the while loop. Theres not much there in our example,
because were keeping it light and only one thing must be in your while loop. Thats
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 hes 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, shell 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.
WP Shout
Page 14 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-inwordpress/">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.
WP Shout
Page 15 of 39
Page 16 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 theres only one post on the page. This is powerful.
As weve said, WordPress has built up some really powerful choice trees.
Lets say you want to customize the way your category archivethe listing of multiple posts
from a single categorywill look. If youve 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 dont 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
archivesnot archives by date, tag, author, etc.
WP Shout
Page 17 of 39
But if you now decide that you only want your changes to apply to one category archivefor
example, Poemsyouve 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 youve 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.
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 issingle taxonomy for
exampleand 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. Its
not exhaustive, but its easy to read. (Its also the image in the previous section.)
Marktime Medias Graphical Version: These are a bit large and unwieldy for many
contexts, but theyre really thorough and rather nice-looking to boot. If youre a real
WordPress nerd you could even use them as your desktop background.
Onward!
WP Shout
Page 18 of 39
WP Shout
Page 19 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 filewell call it abbreviated.phpand 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 youd like to change something around, you only have to change one file.
For claritys sake, heres 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 heres 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>
WP Shout
Page 20 of 39
Now the clever among you may have an interesting but dangerous thought: Why not just use
PHPs include or require functions?
Well, you can, and itll 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() well 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, Id recommend against it.
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 posts
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 youve set. In most default WordPress
themes, and many others, youll see this come out like this:
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
WP Shout
Page 21 of 39
At first glance, this may just look confusing. But all its 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 youre 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. Youll see it in most good
themes you try to edit, and now I hope you know what its doing and why its valuable.
I want to close by mentioning one issue Ive hit my head against: because of the way
get_template_part() works, your local variables in the parent file arent 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, theres 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!
WP Shout
Page 22 of 39
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care
Page 23 of 39
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care
Want to show something? Use a template tag with the_ on the front,
like the_title().
Want to manipulate a value before its shown? Add a get_ to the front of the
template tag, like get_the_title()and dont 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 characterswhich you
would do because you have gone madyoud 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().
WP Shout
Page 24 of 39
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care
WP Shout
Page 25 of 39
WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care
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.
WP Shout
Page 26 of 39
What Not to Do
First off, because of the way WordPress renders pages and makes pretty URLs, you cant 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 its got a huge problem: if anyone ever installs your theme on any other domain,
theyll 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 itll 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.
WP Shout
Page 27 of 39
Page 28 of 39
But they do allow you to pass in the path of the file relative to your theme root as a
function argument.
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
Weve covered a lot of wrong ways and a few right ones. If youve read carefully, you should
never have trouble linking to theme resources.
WP Shout
Page 29 of 39
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.
WP Shout
Page 30 of 39
2
Compounding this problem: Sellers of themes are competing to match each other featurefor-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 dont 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 itll do SEO, itll
appeal to a lot of people.
Page 31 of 39
data by declaring that same content type in a plugin, but most regular WordPress users
cant. 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 tagor category-like system, either for posts or pages or for a custom post type it registers.
(Which it shouldnt have done anyway; see #1.) Again, while this data isnt lost eternally
an expert can recover it with some speedits 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 Lelands point: a theme shouldnt provide shortcodes, or any other
specific means of adding unique-to-the-theme elements to post content. Theres 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,
theres 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 wouldnt have a lot of luck selling your dog toys in a blog-type layout.
Its true: were asking WordPress to do many things beyond what the first creators of themes
envisioned. But it doesnt 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 youre 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 toolsadmittedly not as well-known, well-supported, or integrated into the
core of WordPress as they should be (Brian Krogsgards post about this problem is highly
recommended)that let a theme declare its dependency on plugins. But dont put any of the
WP Shout
Page 32 of 39
users data into your theme unless youre trying to lock them into you forever. While that may be
a business strategy, its not a very good one.)
WP Shout
Page 33 of 39
WP Shout
Page 34 of 39
Make an everything plugin. This is pretty simple if you know only the smallest bit of
PHP. Heres how you do it: Take the entirety of your themes functions.php and put
it inside a new plugin. If youve never created a plugin before but are interested in
trying, I recommend my Minimum Viable WordPress Plugin post. This plugin probably
wont be able to run side-by-side with your creepy themePHP will error at youbut
when youre on a different theme, you may be able to run both the theme and the plugin
and keep everything working. If not, youll 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 sites
shortcodes should be another, etc. This is a better idea overallyoull end up with a more
modular and flexible WordPress site, and you can turn pieces of functionality on and off
independentlybut it does require a bit of thinking about each pieces 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 themes support to
inquire about theme creep and theme modularity. In the worst case, youll discover in
advance that the theme authors support is lackluster, or that theyre not knowledgeable
enough to understand the issues youre asking about. In the best case, you get a futurefriendly WordPress theme with proven support that wont weight you down in the future.
As a theme maker or coder, there is more you can do. We wont 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 shouldnt 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!
WP Shout
Page 35 of 39
Page 36 of 39
/*
Theme Name:
Theme URI:
http://example.com/
Description:
Author:
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 its 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.
Theres one problem with this new theme youll have
made: by default it wont look very good. This is
because WordPress looks for every file first in the
child theme, and then in the parent if it wasnt in
the child. Because our theme now has a virtually
empty style.css filewhich is the main source of
visual styling for a themeyoull 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
themes style.css file into your child
themes style.css file. Now your sites looking
identical to the way it didbut youre 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 themes style.css. If you want to
WP Shout
remove some template tags from your sites single entry template, single.php, youll copy that
file from the parent theme into your child theme and make your changes from there. The child
themes single.php will replace the parents one-for-one across your whole site.
You can edit your theme this way to your hearts content, and because youre on a child theme,
you can update the parent theme without worries. Your changesstyles youll add
to style.css or any replacement template you usewill be safe. Pretty cool, right?
Check out child themes! We love them, and we think you will too.
WP Shout
Page 38 of 39
Summary
Summary
Whew! WordPress themes are simple to use, but theres quite a bit going on under the surface.
On the other hand, the WordPress theme architecture is (mostly) elegantly and thoughtfully
designedso 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 youve enjoyed this book, we have a few suggestions for you:
Keep learning. WordPress gets cooler the deeper into it you goand if youve read and
understood this book, youve gotten a lot of the foundational stuff out of the way.
Say hi. At WPShout, wed always love to hear from you. If this book has left you with a
burning question, tell us about it! Well try to answer, either directly or in a tutorial post.
Stay tuned. Over the next several months, well be developing Mastering the Fundamentals
of WordPress Themes into a full-fledged guide for people wishing to understand the
fundamentals of WordPress development. If youd like to be included on the release list
(and get a 25% discount when the book drops), then email us and well 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!
Page 39 of 39