Creating Custom Category Pages

Now that you’ve picked a theme, created a custom post type, and added a bit of
sample content, you’re ready to start reengineering your site. Your goal is to remove
the “bloggish” details that don’t really fit, and make your site feel like a fine-tuned
custom creation.
The first challenge is to give your visitors a decent way to browse Distinct Furnishing’s
products. Right now, WordPress sorts the products the same way that it sorts
posts—in reverse-chronological order, based on the date you published the post.
While that makes sense for a blog, a news website, and many other types of sites, it
isn’t terribly useful in a product catalog. Visitors who arrive at Distinct Furnishings
probably won’t want to see every item crowded into a somewhat disordered single
page of tiles . Instead, they’ll want to focus on the type of furniture they
need—like a sofa, chair, or table.

This is clearly a job for the WordPress category system. As you already know, you can
browse posts by category by putting the category name in the web address, like this:
http://distinctfurnishings.net/sofas
Of course, you won’t expect your visitors to type this address on their own. Instead,
you’ll supply the links in a post or page, in the Categories widget, or in a menu. Menus
are the most common way that visitors navigate sites.

The menu approach is probably the best browsing experience you can create without
editing your theme. However, it’s not perfect. It has several shortcomings:

• You can’t display different categories of products in different ways. For example,
you might want the sofa-browsing page to look different from the
tables-browsing page.

• You can’t display additional information about a category.

• You can’t control the order of products within a category—WordPress still puts
them in reverse-chronological order by publication date.

However, you can control all these options by customizing the category page template
(also known as a category archive page), which creates the page . For example, when you visit a web address like http://distinctfurnishings.net/
sofas, the category page grabs the products in the Sofas category and displays them.
The stock category page does a decent enough job, but you can do better by editing
your theme.

Advertisements
Creating Custom Category Pages

Cleaning Out the Template

The first step in creating this sort of custom home page is to find the template you
want and prepare it for editing. In virtually all modern themes, the index.php template
is the one you want. It creates a home page with the standard list of posts. (The
only exception is if your theme has a home.php file—if it does, edit that template
instead.) To get started, choose Appearance→Editor and then pick “Main Index
Template (index.php).”
In many ways, the index.php template is like the category.php template you considered
in the first part of this chapter. The heart of both is a loop that extracts and
displays posts. The most significant difference is that category.php uses a narrower
query that includes the posts in just a single category.
You could keep the standard loop in the index.php template and simply change the
way it displays each post. You’ve seen examples that use this technique to highlight
new posts  and change the post order. But here makes
a more radical change—it grabs several separate post lists, by category, and then
displays them. The easiest way to make this happen is to remove the existing loop
entirely and add all new code. In most themes, that means deleting everything
inside the content <div>.
In the PinBlack theme, deleting the loop leaves you with this exceedingly simple
skeleton:

<?php get_header(); ?>
<div id=”content” class=”clearfix”>
</div> <!– end #content –>
<?php get_footer(); ?>

All this template does is add a header and footer to a page. In between is a great
big empty section where you can slot in your own content.

NOTE Remember, the header template (header.php) isn’t just a header—it has the HTML markup that begins
each page, which includes the title, style sheet links, background, and menu. Similarly, the footer template (footer.
php) includes the HTML that ends every page. So even in a simple stripped-down template like the one shown
above, your site ends up with a fully formatted home page, albeit one that doesn’t have any content in it.

Cleaning Out the Template

Adding a Category Description

The first and easiest change you can make to the category page template is adding
a category description. Many themes, including PinBlack, automatically display the
category description on the category page. You don’t even need to edit your theme.
When you first create a category, it doesn’t have a description, but you can easily
add one to the category record. Start by choosing Posts→Categories to see a list
of all your categories, and then click the Edit link under the category you want to
edit. Then type the category description in the Description box.
TIP Although the Description box doesn’t give you the editing conveniences you get when editing a post or
a page, you can still type in any HTML you want. For example you can insert <img> elements that show pictures,
<a> elements that create links, and formatted <div> elements that use classes from the style.css file.

Adding a Category Description

Defining a Custom Post Type with a Plug-In

Creating a custom post type with code really isn’t that bad. As long as you have
the right code in hand, it’s a simple case of copy, paste, and edit. However, even
WordPress gurus get tired of writing code—and exasperated by the way minor typos
can cause big-time headaches.
The problem gets worse if you get more ambitious and decide to add custom taxonomies
to your site. custom taxonomies let
you attach extra bits of information to your custom post types. For example, Distinct
Furnishings might use custom taxonomies to add color, style, and price information
to its products. The problem is that every custom taxonomy needs to be registered
in code, much like every post type, and that adds up to a tedious afternoon.

For all these reasons, most WordPress developers use some sort of plug-in to create
custom post types. Two of the best and most popular are Custom Post Type
UI
(http://tinyurl.com/cust-pt-ui) and Types (http://wordpress.org/plugins/types).
Both work the same way: They add tools to the dashboard that let you define new
posts types and new taxonomies, no coding required.
For example, if you install and activate the Custom Post Type UI, you can follow
these steps to create a custom post type:

1. Choose CPT UI→Add New in the dashboard menu.
This brings you to a management page where you can create a new custom post
type (using the boxes on the left) or a new taxonomy (on the right).

2. Fill in three key details: the name of your custom type, the plural and singular
labels, and an optional description (Figure 14-6).

3. Click Advanced Options.
You’ll see a whack of extra settings (all of which are explained, somewhat tersely,
in the function reference at http://tinyurl.com/reg-cpt).

4. In the Supports section, select the features you want with your custom
post type.
To duplicate the code-only example you saw earlier, you need to tick the Title,
Editor, Featured Image, and Excerpt checkboxes.

5. In the Built-in Taxonomies section, add a checkmark next to Categories if
you want your custom post type to use categories.
You can also switch on the Tags checkbox to use tags with your custom post type.

6. Click Create Custom Post Type.

The Custom Post Type UI plug-in creates the code that builds your custom post
type. You’ll see it in the dashboard menu, exactly as if you added the necessary
code to the functions.php file.

To modify your new custom post type, you need to use the plug-in. Choose
CPT UI→Manage Post Types to see all the post types you created, and to edit
or delete any of them.

Defining a Custom Post Type with a Plug-In

Editing Custom Post Types

I created a custom post type and added some posts that use
it. Now I want to change the custom post type. Is that safe?
You can return to your functions.php file and edit your custom
post type any time, without causing a problem. For example,
you can change the labels that appear in the dashboard,
the features that your custom post type supports, and the
taxonomies it uses.
You might, for instance, create a custom post type for products
that doesn’t support categories, then add some product posts,
and then decide that you actually do want to use categories. No
problem—just change the code in functions.php. When you go
back and edit one of your product posts, the category-picking
box will magically appear.
If you want to remove a custom post type, you can delete
the block of code that creates it in functions.php. However,
you should delete the posts that use your custom post type
first. Otherwise, those posts will continue to live, zombie-like,
even though you can’t see or manage them in the dashboard.
There’s one detail that you should probably never change once
you create a custom post type: its lowercase name. This is the
detail you supply as the first argument you pass to the register_
post_type() function. If you change the name,
WordPress assumes you removed the old custom post type
and you’re adding a new one. As a result, any posts that use
the old custom post type will disappear from the dashboard,
which obviously isn’t what you want.

Editing Custom Post Types

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
to http://tinyurl.com/reg-cpt.

• 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).

UP TO SPEED
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 http://tinyurl.com/reg-cpt, or try
out a custom post type plug-in, which lays out all the possible
options.

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
name”.
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
New.

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 http://distinctfurnishings.net/product/country-stool.

 

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, http://distinctfurnishings.net/product/red-gloss-sofa 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 http://distinctfurnishings.net/sofas, 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 http://tinyurl.com/theme-f.)

The Distinct Furnishings site follows the second approach. It uses the PinBlack
theme (http://tinyurl.com/pinblack), 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.

NOTE
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