Adding New Types of Posts

Throughout this book, you’ve relied on two basic WordPress ingredients: posts and
pages. But WordPress has a semi-secret superpower: It can manage other types of
content, provided you define them first. These are called custom post types.
Consider the Distinct Furnishings site. Its goal is to present a product catalog that
describes the items that it offers for sale. You could put each furniture item into an
ordinary post, but that approach could get messy, especially if you want your site
to feature ordinary news-style postings as well as product postings.
A better system is to create a custom post type called product that’s tailored to the
furniture items you want to show. Using this post type, you can create a separate
product post for each piece of furniture in the catalog.

Product posts (or any type of custom post) are a lot like ordinary posts, except that
they come with extra features. For example, you can choose to put your product
posts in a separate section of your website, organize them in a different way, and
attach different bits of information to them. Custom post types are also a linchpin of
professional ecommerce plug-ins and themes, as you’ll learn at the end of this chapter.

NOTE Custom post types are the gateway between an ordinary blog and a true content-management system
(CMS)—in other words, they let you create a site that can display any type of content you create.

Here’s the catch: Creating a custom post type is a bit of work. Not only do you need
to define a custom post type (using code or a plug-in), you also need to alter your
theme to use it. In fact, without these changes, your custom post type won’t appear
on your site at all.
In the following sections, you’ll consider two ways to create a custom post type for
products. First, you’ll consider the raw code approach, which requires nothing more
than the WordPress dashboard and a bit of bravery. Then, you’ll pick up a plug-in
that can do the same job more efficiently.

Defining a Custom Post Type in Code

To create a custom post type, you begin by choosing a name for it. This name should
be short, with all lowercase letters and no fancy characters. (Hyphens are technically
allowed, but can cause various annoyances, so avoid them.) Examples of good
post type names include review, recipe, book, employee, exhibit, article, and so on.
Distinct Furnishings uses a custom post type named product.
Someday in the future, WordPress may offer a dashboard menu for creating custom
post types, but today it asks you to do the work the hard way, by running a snippet
of code. You add this code to your theme’s functions.php file—the all-purpose theme
extender you use to unlock new features (page 500).
To edit functions.php, choose Appearance→Editor in the dashboard, and then click
the “Theme Functions (functions.php)” link on the right. Scroll down past all the
code that’s already there. You can add your code at the end.
TIP If you’re working with a child theme, you won’t already have a functions.php file, but you can make
one (page 490). Once you create a new, blank functions.php file, write <?php on the first line to begin a block
of PHP code. Then add the code that registers your custom post type underneath.
The easiest way to register a custom post type is to copy a ready-made block of code
and change the details to suit your post type. Here’s an example that you can paste
straight into the functions.php file on your site, provided you edit the details in bold:

function create_product_post_type() {
$labels = array(
‘name’ => ‘Products’,
‘singular_name’ => ‘Product’
$args = array(
‘labels’ => $labels,
‘public’ => true,
‘supports’ => array( ‘title’, ‘editor’, ‘thumbnail’, ‘excerpt’ ),
‘taxonomies’ => array( ‘category’ ) );
register_post_type( ‘product’, $args );
add_action( ‘init’, ‘create_product_post_type’ );

This code has two pieces. First, it includes a custom function named create_product_
post_type(), which defines the custom post type. Then, it uses the add_action()
function to tell WordPress to run the create_product_post_type()function when
it initializes the theme. This makes sure that your site starts out with your custom
post type, ready to go.

NOTE The name you use for your custom-type-creating function is unimportant, as long as you’re clear,
consistent, and you don’t use the name of an existing function. The name create_product_post_type()
makes sense in this example, because it registers a new custom post type named product. If you created a custom
post type for movie reviews, for example, you might choose to name the function create_review_post_
type(), but this detail doesn’t change the way the code works.

Inside the create_product_post_type() function is the meat of the code: the instructions
that determine the key details for your new post type. When registering a
custom post type, you have the chance to specify an avalanche of settings, including
many minor details. The current example includes just the essentials:

• Name and singular name. These are the descriptive titles that appear in the
dashboard,  Choose names that match your post type.
In the Distinct Furnishings example, the custom post type is product, so it makes
sense to use the singular name Product and the plural name Products. (But it’s
not always as straightforward as adding an “s.” For example, if you have a custom
product type called story, you’d want to use the titles “Story” and “Stories.”)

• Public. If a post type is public, it appears in the dashboard, allowing you to
manage all the posts of that type. In the case of Distinct Furnishings, that means
you can log in to the dashboard and create new products or edit existing ones,
as you’ll see shortly. Private post types are hidden from view and managed with
code. (For example, plug-ins sometimes use private post types for their own
information-storing purposes.)

• Supports. A custom post type can use some or all of the features of ordinary
posts and pages. You get the features you want by including them in a list. In
this example, products support featured images and excerpts, but not revisiontracking
or comments. For the list of features from which you can choose, go

• Taxonomies. As you learned earlier in this book, a taxonomy is a way of organizing
posts. In this example, the new product post type uses the standard
category organization system, as do posts. The product post type doesn’t elect
to use tags—although it could, if you replaced (‘category’) with (‘category’,
‘post_tag’). But the most powerful (and complex) approach is to create your
own taxonomy. You’ll dip your feet into those waters.

Finally, the register_post_type() function is the part that works the magic, creating
the custom post type according to the recipe you provide. When registering a
custom post type, you need to provide the all-lowercase name you picked, which
is the key bit of information that identifies your type.

Once you add this code to the functions.php file, it’s time to see if you successfully
created the post type. Click the Update File button to store your changes, and then
refresh your browser. Assuming all is well, your new post type will appear in the
dashboard menu (Figure 14-3).

Creating a Custom Post Type That Suits Your Site

The Distinct Furnishings example uses a custom post type
named product because each post represents a piece of furniture.
However, you could just as easily create a custom post
type to represent something else, like movie reviews, how-to
articles, celebrity biographies, employee resumés, recipes, or
any other kind of content (so long as it’s made up of text and
pictures). For example, here’s how you might alter the code you
just saw to define a custom post type for restaurant reviews:

function create_review_post_type() {
$labels = array(
‘name’ => ‘Reviews’,
‘singular_name’ => ‘Review’
$args = array(
‘labels’ => $labels,
‘public’ => true,
‘supports’ => array( ‘title’, ‘editor’,
‘thumbnail’, ‘excerpt’),
‘taxonomies’ => array( ‘category’ )
register_post_type( ‘review’, $args );
add_action( ‘init’,
‘create_review_post_type’ );

There are many more details you can configure in your custom
post type. For example, you can tweak the text that appears
in various places in the dashboard when you add or edit posts
that use your custom post type. For more information, refer
to the function reference at, or try
out a custom post type plug-in, which lays out all the possible

There’s one more task to carry out before you continue. Because of a quirk in the
way WordPress handles permalinks, you need to force it to refresh its permalink
settings when you create a custom post type. If you don’t, WordPress may fail to
show posts that use your custom post type. To fix this problem, follow these steps:
1. Choose Settings→Permalinks in the dashboard.
2. Make sure you’re using one of the pretty permalink settings, such as “Post
3. Click Save Changes, even if you haven’t changed anything.
Now you’re ready to start adding content to your site.

Creating Sample Content
Now that you have a custom post type, you’re ready to put it to use by creating some
sample posts. Adding a post that uses a custom post type is the same as adding an
ordinary post, but instead of choosing Posts→Add New, you choose Products→Add

Just like an ordinary post, your new product post gets its own page and permalink.
And just like an ordinary post, you click Preview to take a look at the work in progress
and Publish to add it to your site. When you finish, choose Products→Products to
look at a list of all the products you added (Figure 14-5).
NOTE Keen eyes will notice that the permalink for a custom post type includes the name of the custom
post type. For example, if you create a product named Country Stool, WordPress gives it a permalink like http://

Just like an ordinary post, your new product post gets its own page and permalink.
And just like an ordinary post, you click Preview to take a look at the work in progress
and Publish to add it to your site. When you finish, choose Products→Products to
look at a list of all the products you added .

NOTE Keen eyes will notice that the permalink for a custom post type includes the name of the custom
post type. For example, if you create a product named Country Stool, WordPress gives it a permalink like


Making Your Custom Post Type Appear on Your Site

So far, life with custom post types is good. In the Distinct Furnishings site, you can
easily review your products and add new ones. But dig a little deeper, and you’ll find
a glaring problem. Although you can visit each product post using its permalink (for
example, to take a look at the
Red Gloss Sofa), your products won’t appear in any of WordPress’s archive pages.
These include the pages that display a list of posts by author, category, tag, or date,
and the home page that shows the reverse-chronological listing of all your posts.
In other words, if you hit up the home page, you’ll find it empty. And if you visit a
category page like, you won’t see the products
you put in the Sofas category.

There are two ways to fix this. The most versatile approach (and the one preferred
by WordPress experts), is to create your own archive pages that use custom queries
to pull out the product posts you want, in the order you want them. You’ll learn how
to do that later. But in the meantime, you can
use a simpler solution: Tell WordPress to always include your custom post type in
all its archive pages. You do that by revisiting the functions.php file and adding one
more block of ready-to-roll code:

function add_product_to_archives( $wp_query ) {
$types_array = array( ‘post’, ‘product’ );
if( is_archive() && empty( $query->query_vars[‘suppress_filters’] ) ) {
set_query_var( ‘post_type’, $types_array );
add_action(‘pre_get_posts’, ‘add_product_to_archives’);

This code tells WordPress to include product posts in all its archive pages. (If you
created a different custom post type, substitute its name instead of product in the
code above.)
Now if you visit the Distinct Furnishings home page, you’ll see a list of all its products.

Adding New Types of Posts

Planning Your Site

The first step to building an advanced, customized site is to get out a notepad and
start planning. Before you set fingers to keyboard, you should ask (and answer) a
few questions:

• What type of content will your site feature?
• How will your content be arranged, and how will visitors browse your site?
• Will your content use posts or pages or both?
• Do you need to create separate types of posts for different content?

It’s important to think about these questions early on, because you need to consider
how you want visitors to interact with your site. And that, in turn, determines the
kind of changes you need to make to your theme. In the case of Distinct Furnishings,
for example, the site’s job is to display information about the different pieces
of furniture the company sells. Visitors will arrive at the site and browse through
the items that interest them. Essentially, the Distinct Furnishings site is a product
catalog, which is a common type of advanced WordPress site.

Picking a Theme

Every WordPress theme has similar underpinnings, but no two themes are quite the
same. If you start out editing a theme that isn’t well suited to your site, you’ll create
extra work for yourself. So before you commit to a theme, make sure you’ve got the
best, most workable one for your needs.
There are many ways to pick a good theme for customization:

• Some WordPressers pick one they understand (like Twenty Twelve) and use
that in all their customization projects.
• Some web designers pick a theme that’s as close as possible to the final result
they want. This means they have much less customization to do, but it also forces
them to spend time learning the subtly different workings of a new template.
• Some WordPress pros use a heavily stripped-down theme, which provides very
little beyond the core WordPress code. This way, they don’t need to worry about
removing built-in features and embellishments they don’t want, but it also means
they need to supply the majority of the markup and styles that format the site,
which takes time and requires some serious web design skills.
• Some WordPressers favor theme frameworks, which are simple, foundational
themes designed for other developers to extend. The drawback is choice and
complexity: There are many theme frameworks to choose from, and they all
have their own subtly different structure. (To learn more, read what WordPress
has to say at

The Distinct Furnishings site follows the second approach. It uses the PinBlack
theme (, which already has most of the right layout and
formatting in place .

Before you go any further, you need to decide whether you want to work on a child
theme  or the original theme files. As you learned, child
themes are always the right choice when you make cosmetic changes to a theme
you love. They’re also a good idea if you plan to make targeted changes to specific
aspects of a theme, while leaving the rest of it alone. But if you plan to make extensive
changes that will require you to modify most of the template files in a theme, a child
theme doesn’t make as much sense. Since you’ll override almost all the functionality
in the original template, there’s little reason to use a child theme that retains its
relationship with its parent.

Once again, there’s no clear-cut answer for all situations. It depends on how complex
a theme you start with, and how heavily you plan on customizing it.

• If you decide to create a child theme that extends an original theme, follow the
instructions in post “how-to-use-child-theme-configurator”.

• If you decide to create a completely new theme that replaces the original theme,
continue reading the next section. This is the approach the Distinct Furnishings
example follows with the PinBlack theme.

Creating a Custom Copy of a Theme

In theory, you can edit any theme in the dashboard without taking any special steps.
But doing so is risky. Eventually, the creator of the original theme will distribute an
update, and it’s all too easy to accidentally install the update and wipe out all your
carefully crafted customizations.

To protect yourself, create a copy of the theme that WordPress won’t ever try to
update. Here’s how:

1. Download the theme files to your computer.
You can do this two ways. One is to use an FTP program and drag the appropriate
theme folder (say, pinblack) from your site’s /wp-content/themes folder
to your computer.
The other option is to visit the WordPress themes directory at http://wordpress.
org/themes. Search for the theme you’re using, view it, and then click Download.
WordPress stores the theme files in a ZIP file. Double-click the ZIP filename to
peek inside, find the theme folder, and copy that folder to your computer (say,
the desktop) so you can edit the files it contains.

2. Open the theme’s style.css file in a text editor.
Usually, that means Notepad on a Windows computer and TextEdit on a Mac.
At the top of the file, you see the header comment with its basic information
about the theme.

3. Change the theme name.
For example, where it says this:
Theme Name: PinBlack
Change it to:
Theme Name: PinBlack_Custom

This is the name WordPress will use in the dashboard for the copied theme.

PinBlack_Custom is a good theme name, because it clearly communicates that this is a customized
version of the original PinBlack theme. PinBlack2 would be a bad choice, because the person who created PinBlack
might use that name to denote a significant revamp of the original theme.

4. Remove the theme URL.
That’s the line that starts with “Theme URI.” Find it and delete it. This severs the
link between your theme and the original one, ensuring that any theme update
won’t overwrite your customized files.

5. Rename the theme folder to match the theme name.
For example, if you used the name PinBlack_Custom, you might rename the
theme folder pinblackcustom. It doesn’t really matter what name you use, as
long as you change the folder name from the original (pinblack) in some way.

6. Upload the new theme to your site.
You can do this two ways, too. The most direct is with an FTP program, where
you drag the new theme folder (say, pinblackcustom) from your computer to
your site’s /wp-content/themes area.
The other option is to ZIP up your theme folder, and then upload it using the
dashboard. Once you create the ZIP file, choose Appearance→Themes, click
the Install Themes tab, and then click Upload. Select your ZIP file (click Browse
or Choose File—the button’s name depends on your browser), and then send it
off to your site (click Install Now).
Either way, once you upload the custom version of your theme, you can start
using it.

7. Choose AppearanceÆThemes, point to your theme, and then click Activate.

Planning Your Site

Extending WordPress with Functions.php

Some WordPress themes contain one PHP file that isn’t a template, named functions.
php. Experienced theme designers place important parts of their code here, and
then call that code from their template files when they need it. WordPress gurus also
use the functions.php file to add other features, like new shortcodes and widgets,
so they don’t need to create a complete plug-in.
All these tasks are advanced operations, best kept to WordPress gurus. However,
even people with no PHP experience can use the functions.php file to unlock extra
WordPress features. Usually, you do that by copying a few lines of code you read
about online (or in a book), and pasting them into the functions.php file in the
theme editor.
For example, in Chapter 10, you used WordPress’s auto-embed feature to turn certain
types of website addresses into embedded objects, like Flickr slideshows and
YouTube videos. Normally, WordPress turns off this handy feature in widget areas,
like the sidebar. But those in the know can enable shortcodes and embeds in widget
areas with just a couple of lines in the functions.php file. Figure 13-18 shows the result.
The functions.php file works a bit differently from the template files you’ve learned
about so far. The key quirk is that the functions.php file in your child theme extends
the functions.php file in your parent theme; it doesn’t replace it. For that reason, you
can’t simply copy the functions.php file from your parent theme to your child theme.
You need to create a new, empty text file on your computer, change its name to
functions.php, and then upload that new functions.php file to your child theme folder.
If you use the Orbisius Child Theme Creator plug-in, your job is easy. Follow the
process described on page 490 to create a new, blank functions.php file, but don’t
copy any content to that file.

WARNING If you accidentally copy the functions.php file from your parent theme to your child theme,
your site will stop working. That’s because functions.php is full of important routines that Twenty Twelve uses,
and having two copies of this code is enough to blow WordPress’s mind. The only fix (if you disregard this warning
and put the full functions.php file in your child theme folder) is to log in to your site with an FTP program and
delete the copied functions.php file.
Once you add the blank functions.php file to your site, you can edit it in the Edit
Theme page, as you can any other theme file. To enable widget-embedding, as
shown in Figure 13-18, you need to add these lines:

add_filter( ‘widget_text’, array( $wp_embed, ‘run_shortcode’ ), 8);
add_filter( ‘widget_text’, array( $wp_embed, ‘autoembed’), 8 );

Now you can put an auto-embed URL in a Text widget, just as you can in a post

Extending WordPress with Functions.php

A Basic Editing Example

By this point, you’ve digested a fair bit of WordPress theory. It’s time to capitalize
on that by editing a template file.
You’ll begin with an example that seems simple enough. You want to remove the
“Proudly powered by WordPress” message that appears at the bottom of every
page on your site, just under the footer widgets (Figure 13-15). (It’s not that you’re
embarrassed by WordPress. You just can’t help but notice that none of the other
big-gun WordPress sites have this message slapped on their pages. Sometimes,
being professional means being discreet.)

Start by examining the list of templates in Table 13-2. In this case, the footer.php
file is the obvious candidate. It creates the entire footer section, widgets and all,
for every page.

Once again, you need to start with a child theme (page 462). If you don’t, you can
still customize the footer, but your hard-won changes will vaporize the moment you
install a theme update.
Here’s where things get a bit more awkward. As you know, WordPress templates are
really a collection of many template files. To change a template, you need to figure
out the changes you want to make to your pages, and then find the template file
responsible for that part of the page (single.php, comment.php, and so on). Then
you add a new version of that template file to the child theme. That new template
will override the one in the parent theme.
You do this by copying the template file you want to edit from the parent theme to
your child theme and then making your changes. In this example, that means you
need to copy the footer.php file in the twentytwelve folder and paste it into the
twenty-twelve-reboot folder.

NOTE The child theme’s version of a template completely overrides the parent theme’s copy of the template.
In this example, that means WordPress ignores the original version of the footer.php file, which is in the original
theme folder (twentytwelve). You can refer to it anytime to check the code or copy important bits, but WordPress
won’t run the code anymore.

Footer.php is one of WordPress’s simpler template files. But even simple templates
have a fair bit of boilerplate to wade through.
In this section, you’ll look at the entire contents of footer.php. You don’t always need
to take this step, but it’s good practice when you’re just starting out and trying to
make sense of WordPress’s template system.
If you’ve written web pages before, you probably know that programming code,
like JavaScript, needs to be carefully separated from the HTML on the page. The
same is true for PHP, although it has its own special syntax. Every time a block of
PHP code appears, it starts with this:
Similarly, the following character sequence marks the end of a block of PHP code:
You can see this system at work at the very beginning of every template file, where
there’s a block of PHP that has no real code at all, just a long comment. The comment
lists some basic information about the template. Here’s what you see in footer.php:
* The template for displaying the footer.
* Contains footer content and the closing of the #main and #page div elements.
* @package WordPress
* @subpackage Twenty_Twelve
* @since Twenty Twelve 1.0
The next line is a puzzling bit of HTML that looks like this:
</div><!– #main .wrapper –>
Even seasoned HTML veterans will be a bit thrown off here. The </div> tag closes
a <div> element. But you haven’t seen an opening <div> tag, so this code snippet
seems a bit strange.
It makes more sense when you remember the way WordPress stitches together a
page, as shown in Figure 13-14. The <div> element was opened, but it happened when
WordPress processed an earlier template file (header.php). The HTML comment in
the line above (<!–#main .wrapper –>) is WordPress’s way of reminding you that
the </div> in that line is the closing element for a <div> that has the ID main and
the class .wrapper. In other words, it’s the closing element for the <div> that holds
the main content of the page.

The next line of HTML is easier to interpret. It identifies the beginning of the footer
content. This section has the ID colophon, which you might remember from Table 13-1.
<footer id=”colophon” role=”contentinfo”>
The next line starts a new <div> element and gives it the ID site-info. The creators of
the Twenty Twelve theme chose that name because this is the section of the page
that indicates some basic information about how the site was created (in other
words, “Proudly powered by WordPress”).
<div id=”site-info”>
The next bit is another block of PHP code, but it’s compressed into a single line:
<?php do_action( ‘twentytwelve_credits’ ); ?>
The do_action() function is a WordPress feature found throughout its template
files. It’s a notification mechanism—it signals when something is about to happen
(for example, that the page credits are about to be shown). Hardcore WordPress
developers can write instructions that react to one of these notifications, but the
do_action() function is no help in your mission to change the footer.
NOTE A function is a block of programming code stored somewhere other than the page it appears on.
WordPress is full of useful functions, and do_action() is one of many. To browse the full catalog of functions
and find out what they do, visit
The section that appears after the do_action() function is the part of the footer
template you’ve been looking for. It’s a link that displays the “Proudly powered”
<a href=
“<?php echo esc_url( __( ‘’, ‘twentytwelve’ ) ); ?>”
title= “<?php esc_attr_e( ‘Semantic Personal Publishing Platform’,
‘twentytwelve’); ?>” rel=”generator”>
<?php printf( __( ‘Proudly powered by %s’, ‘twentytwelve’ ),
‘WordPress’); ?>
The markup looks a bit complicated, because there are three PHP code statements
embedded inside the <a> element. The first one generates the actual link address,
the second one generates the title, and the third one generates the text inside the
<a> element. You don’t need to understand exactly how these statements work to
realize that this is the part you want to change. But first, scan through the rest of
the footer template to make sure you understand what’s going on.
It’s pretty straightforward. First, footer.php closes the <div> and <footer> elements.
Then it closes another <div> that represents the entire page.
</div><!– .site-info –>
</footer><!– #colophon –>
</div><!– #page –>

Next, the footer template triggers WordPress’s wp_footer() function.
<?php wp_footer(); ?>
This is a bit of WordPress infrastructure. Many plug-ins wait for this call and then
do something important. Removing this line can cause those plug-ins to break, so
it’s best to leave it in, even though it isn’t doing anything right now.
Finally, the template closes the <body> and <html> elements, proving that you
have really and truly reached the end of the page. WordPress won’t call any more
templates into action, or add any more content after this point.
Now you’ve found the culprit—the piece of the WordPress template you want to
change. In this example, it’s a single <a> element.
You could delete the <a> element completely, or you can replace it with some text
of your own, like this:
&copy; Copyright 2014 Magic Tea House
The &copy; is a character entity, an HTML code that inserts a special character—in
this case, a copyright symbol.
If you consider yourself a bit of a PHP whiz, you can get fancier in your footer. For
example, instead of sticking in the current year for the copyright notice, you could
ask PHP to do that for you.
First, you need to explicitly tell WordPress that you need PHP’s help. You do that by
adding the <?php and ?> character sequences. You’ll put your code inside.
&copy; Copyright <?php [ Your code goes here. ] ?> by Magic Tea House
Next, you need a PHP command. In this case, it’s the trusty echo command, which
means (in PHP language) “take the result of the next statement, and spit it out onto
the page.”
&copy; Copyright <?php echo ?> by Magic Tea House
But what exactly do you want to spit out? That’s the current date, which you can fetch
with the help of a function built into the PHP language, called date(). Unsurprisingly,
the date() function displays the current date. But by supplying the capital letter Y,
you tell the date() function that you’re interested only in getting the current year.
&copy; Copyright <?php echo date(‘Y’); ?> by Magic Tea House
Like every line of PHP code, you indicate the end of a statement by adding a semicolon
at the end (;)
This completes the example, and drives home a clear point: Even the most straightforward
theme-editing tasks require a bit of slogging.

TIP Since the changes you need to make to the footer.php template are relatively small in this example, it’s
easy enough to do all your editing in the dashboard. For more significant changes, you may want to copy the
theme file to a text editor on your computer, work with it there, and then copy it back to the Edit Themes page
when you finish. And if you decide to edit a theme on your computer, it’s worth considering a text editor that has
a few more frills. For example, Windows users can grab the free Notepad++ program (http://notepad-plus-plus.
org), which uses color-coded text to distinguish the different ingredients in PHP code.

A Basic Editing Example

Delving into the Loop

WordPress experts talk in hushed tones about “the loop,” which is the heart of
WordPress. Its job is to fetch content from your website’s database, one piece at a
time, until it reaches the post limit (that’s the “Blog pages show at most” option in
the Settings→Reading section of the dashboard).
The loop appears in many templates. WordPress uses it to create the main list of
posts on the home page (index.php), the list of results after a search (search.php),
and the list of articles you see when you browse by category, tag, author, or date
(category.php, tag.php, author.php, and date.php, or archive.php when one of
the former is missing). The loop even appears on Twenty Twelve’s showcase page
(showcase.php), twice—first to grab the featured posts that it puts up top, and again
to grab the recent posts that it shows underneath.

In the following example, you’ll take a look at the loop in the index.php file and
change the way it works by adding a new feature: the ability to highlight recent

Your first task is to prepare your template. You can copy the index.php file into your
child theme folder using an FTP program, or you can use the Orbisius Child Theme
Creator plug-in to copy it for you.

The next step is to dig through index.php to get a handle on what’s going on and
what area you need to change. Overall, index.php has this structure:

<?php get_header(); ?>
<div id=”primary”>
<div id=”content” role=”main”>
[ The stuff for displaying posts goes here. ]
</div><!– #content –>
</div><!– #primary –>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

This boils the template down to its essentials. As you can see, the template calls
other templates to create the page’s header, sidebar, and footer. In the middle of
this action are two <div> elements, and inside them is the heart of the index.php
template and the loop. This is the part you’ll focus on.
The first ingredient here, inside the <div> elements, is a block of conditional logic—
code that tests a condition, and takes different actions depending on whether that
condition is true or false. Essentially, the template here uses PHP to ask a question:
Are there any posts?
Here’s how the template structures the conditional logic:

<?php if ( have_posts() ) : ?>
[ If there are posts, you end up here. ]
<?php else : ?>
[ If there are no posts, this section shows the “sorry” message.]
<?php endif; ?>

The have_posts() function gets the answer to the question, “Are there any posts?”
If there are, the condition is true, and the first section springs into action. That’s the
part you’re interested in. (If there aren’t any posts, the condition is false, and you can
let the template handle it in the usual fashion, by showing an apologetic message.)
So what takes place inside the first section, which runs as long as your site has at
least one post? The code starts by adding a navigation link, if necessary. This is the
link that appears before the post list and lets visitors step forward to newer posts.
(If your guest is already viewing the most recent post, this link doesn’t show up.)
Then the code triggers the loop (shown here in bold), and ends by inserting another
navigation link—the one that lets readers step back to see older posts.

<?php twentytwelve_content_nav( ‘nav-above’ ); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( ‘content’, get_post_format() ); ?>
<?php endwhile; ?>
<?php twentytwelve_content_nav( ‘nav-below’ ); ?>

The actual loop comes down to just three lines. The while and endwhile commands
delineate the start and end of the loop. As long as you have posts, the loop keeps
running. Every time it runs, it grabs a post, using the WordPress function the_post(),
and feeds it to the single line of code inside. This code is less exciting—it simply farms
out the work of displaying the post to one of the content templates you learned
about earlier, using the get_template_part() function.
Although the code doesn’t seem that exciting right now, there’s a lot you can do
if you wedge yourself inside the loop, between the while and endwhile lines. Currently,
there’s just a single line of code there, but you can expand it to suit your
needs. For example, before the code calls get_template_part() to display a post,
you can run some extra code that does something more clever, like change the
post’s formatting based on one of the post details. Examples include making the
post look different based on its category, author, or publication date. The latter is
what this example does.

The final step is to add the code that checks the post’s date and decides whether or
not to highlight it. Here it is, inside the loop you saw earlier. The new code is boldfaced:

<?php while ( have_posts() ) : the_post(); ?>
$postdate = get_the_date(‘Y-m-d’);
$currentdate =
if ($postdate == $currentdate) {
echo ‘<div class=”newpost”>’;
} else {
echo ‘<div>’;
<?php get_template_part( ‘content’, get_post_format() ); ?>
<?php endwhile; ?>


To understand what’s taking place, you need to examine the code one line at a time.
First, it uses a WordPress function named get_the_date(), which returns the date
the current post was published.

$postdate = get_the_time(‘Y-m-d’);

WordPress takes the result from get_the_date() and puts it into a variable (a storage
slot in memory) named $postdate. That way, the code can use the date stored
there at a later time, when the function compares dates.

NOTE It doesn’t matter what you call your variables, as long as you’re consistent. (So you can’t call the
variable $postdate in one place and $date_of_post in another, because you’ll end up creating two separate
variables.) However, your variable names must start with the dollar sign ($), which has the side effect of making
them easily recognizable.

The next line of code creates a second variable, named $currentdate. It stores the
current date, as retrieved by the PHP date() function, which you saw earlier (page
494). Only now the date is returned in a slightly different format, so it matches up
with the publication date format WordPress uses with posts.

$currentdate = date(‘Y-m-d’);

The moment of drama occurs next. An if statement compares the two variables (in
this case, the two dates) to see if the current date matches the publication date (in
other words, to see if the post was published today). If the answer is yes, then the
code adds a new <div> element, with the class name newpost.

if ($postdate == $currentdate) {
echo ‘<div class=”newpost”>’;
If the answer is no, then the code adds a <div> that doesn’t use any class name.
} else {
echo ‘<div>’;

Either way, the code tacks on the closing </div> element at the end of this block of
content, after it inserts the post content into the page.

<?php get_template_part( ‘content’, get_post_format() ); ?>

NOTE This code may seem slightly magical, because it relies on a tight combination of PHP commands
and WordPress functions that you haven’t seen before. Obviously, you wouldn’t be able to cook up this sort of
code on your own. However, you will be able to grab this sort of code from one of the many WordPress recipe
(page 503), and insert it into your templates when you need it. And the more you do that, the easier it’ll
be to recognize the code you want to change, and the more comfortable you’ll be adjusting that code to solve a

Right now, the revised template doesn’t have much of an effect. All it does is add a
<div> element around the post content. However, this <div> gives you a new way to
apply a customized style. You do that by creating a style rule for the newpost class.
Here are the style rules that create the effect shown in Figure 13-17. The first rule
adds the border, spacing, and background color around the post. The second rule
targets the link in the heading, which holds the post title, and gives it large red text.

.newpost {
padding: 8px;
border: 2px solid darkgray;
border-radius: 10px;
background-color: lightyellow;
margin-bottom: 50px;
.newpost h1 a {
font-size: 2.5em;
color: red;

This two-part approach—using the PHP code to add a style, and then defining the
style—is a common technique in theme customization. It gives you the most flexibility,
because you can change the formatting anytime, without editing the template
and wading through the PHP again.

Delving into the Loop

Updating a Child Theme

What happens when I update a theme that uses customized
Child templates don’t work in exactly the same as child styles.
Child styles extend style rules already put in place by the parent
theme. Even if the parent gets a new, updated style.css file,
the child styles remain, and WordPress applies them on top
of the parent styles.
But page templates don’t extend parent templates, they replace
them. As soon as you add footer.php to your child theme,
WordPress starts ignoring the footer.php in the original theme.
That means that if you update the parent theme and change
the original footer.php file, no one really notices.
This is probably the safest way to handle theme updates,
because there really isn’t a way that WordPress could combine
two versions of a template. However, it means that if you
plan to customize all the templates in a theme, you probably
shouldn’t create a child theme. Instead, you may as well build
a completely separate theme of your own.

Updating a Child Theme

Introducing the Template Files

Every theme uses a slightly different assortment of templates. The WordPress staple
Twenty Twelve uses a fairly typical set of about 30 templates.
You can recognize a template by the fact that its filename ends with .php. Although
template files hold a mix of HTML and PHP, the .php extension tells WordPress that
there’s code inside that the WordPress engine needs to run before it sends the final
page to a browser.
Even though a template is just a mix of HTML and PHP, understanding where it fits
into your site can be a bit of a challenge. That’s because every page WordPress
stitches together uses several template files.
For example, imagine you click through to a single post. WordPress has a template,
called single.php, that creates the page on the fly. However, single.php needs help
from a host of other templates. First, it inserts the contents of the header.php
template, which sits at the top of every page in a WordPress site. The header.php
file takes care of basics, like linking to the style sheet, registering some scripts,
and showing the header section, complete with the top-level menu. (Some themes
farm out the menu-creation work to yet another template file, but Twenty Twelve
doesn’t go that far.)
Next, the single.php file adds the Previous and Next navigation links to the post,
and then calls out to another template to display the actual post. If it’s a regular
post, it uses content.php, but the Twenty Twelve theme has a number of specialized
alternatives for different post formats. For example, an “aside” post (page 203) uses
the content-aside.php template, a “status” post uses content-status.php, and so on.
Finally, the single.php template ends by calling three more templates into action. The
comments.php template creates the comments section, the sidebar.php template
adds the widgets on the right, and the footer.php template ends the page.
If you’re going cross-eyed trying to follow this template assortment, Figure 13-14
shows how it all breaks down.
At first glance, this system seems just a bit bonkers. How better to complicate life
than to split the code for a single page into a handful of template files that need to
work together? But in typical WordPress fashion, the design is actually pretty brilliant.
It means that a theme designer can create a single template file that governs
a repeating site element—like a header—and use it everywhere, without needing to
worry about duplicating effort or being inconsistent.

When you edit theme styles, your first challenge is finding the right style rule to
. When you edit templates, the first challenge is finding the right template
file to modify
. Table  can help you get started. It describes the fundamental
templates that almost every theme, including Twenty Twelve, uses.

Keep in mind, however, that themes commonly add extra templates to create the
formats for different types of posts and pages, and to handle special formatting (for
example, to create different layouts that move the sidebar around). You may also
decide to add extra templates of your own (for example, to change the way your
site presents specific categories or authors.




This is a theme’s main template, and the only one
that’s absolutely required. WordPress uses it if
there’s no other, more specific template to use.
Most themes use index.php to display a list of
posts on the home page.


Displays the banner that appears across the
top of every page. Often, header.php includes a
navigation menu.


Displays the footer that stretches across the
bottom of every page.


Shows the sidebar widget area. Twenty Twelve
also has a more specialized sidebar-front.php
template that creates the footer area for pages
that use the Front Page template.

single.php Displays a single post.

Shows a static page. Themes often have additional
page templates that let you create different
“flavors” of pages (page 233). For example,
Twenty Twelve adds a full-width.php template
that creates a page that doesn’t include a sidebar
and a front-page.php template that includes a
two-column widget area in the footer.


Displays the content of a post or page. Some
themes create many different content templates,
for different types of posts and pages. Twenty
Twelve, for instance, has eight content templates.
An ordinary post uses content.php, a page uses
content-page.php, and special post formats
(page 202) use a corresponding template (for
example, asides use content-aside.php).


Displays the comments section after a post or


Shows the attachment page for images—what
you see when you click a picture in a post, if
you’ve set the Link To setting (page 336) to
Attachment Page.


Lists posts when you browse by author, category,
tag, or date. Or you can use one of the four more
specific templates listed next.


Lists posts when you browse a category. You can
also create templates that target specific categories,
like category-tea.php for a category with
“tea” as its simplified name


Lists posts when you browse by tag. You can also
create templates that target specific tags, like


Lists posts when you browse by author. You can
also create templates that target specific authors,
like author-grabinksy.php.


Lists posts after you execute a search.


Displays an error message when the requested
post or page can’t be found.

Introducing the Template Files