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

Editing the Code in Your Theme THEME

When you want to customize the appearance of a theme, the first place you should
look is the style.css file. But if you need to make more dramatic changes—for example,
revamp the layout, change the information in the post list, or add new widget
areas—you have to go further. Your next step is to consider the theme’s template files.
A typical theme uses anywhere from a dozen to 50 templates. If you crack one
open, you see a combination of HTML markup and PHP code. The PHP code is the
magic ingredient—it triggers the specific WordPress actions that pull your content
out of the database. Before WordPress sends a page to a visitor, it runs all the PHP
code inside it.
Writing this code is a task that’s well beyond the average WordPress website owner.
But that’s not a problem, because you don’t need to write the code yourself, even
if you’re building a completely new theme. Instead, you take a ready-made page
template that contains all the basic code and edit that file to your liking. Here are
two ways you can do that:
• Change the HTML markup. Maybe you don’t need to change the code in the
template file at all. You might just need to modify the HTML that wraps around
it. After all, it’s the HTML (in conjunction with the style sheet) that determines
how your content looks and where it appears.
• Modify the PHP code. You start with a template full of working code. Often, you
can carefully modify this code, using the WordPress documentation, to change
the way it works. For example, imagine you want the list of posts on the home
page to show fewer posts, include just post titles or images instead of content,
or show posts from a specific category. You can do all this by adjusting the code
that’s already in the home page template.
Of course, the more thoroughly you want to edit the PHP, the more you need to learn.
Eventually, you might pick up enough skills to be an accomplished PHP tweaker.

UP TO SPEED

Learning PHP

The actual syntax of the PHP language is beyond the scope of
this book. If you want to develop ninja programming skills,
there are plenty of great resources for learning PHP, whether
you have a programming background or are just starting out.
Don’t rush off just yet, however, because while learning PHP
will definitely help you customize a WordPress theme, it may
not help you as much as you expect.
Learning to customize a WordPress template is partially about
learning PHP (because it helps to understand basic language
details like loops, conditional logic, and functions). But it’s
mostly about learning to use WordPress’s functions in PHP
code (see the Note on page 493 for more about WordPress
functions). For that reason, you’ll probably get more practical
value out of studying WordPress functions than learning the
entire language, unless you plan to someday write dynamic
web pages of your own.
To get started with WordPress functions, check out the function
reference at http://tinyurl.com/func-ref. To learn more about
PHP, start with the absolute basics with the tutorial at http://
tinyurl.com/ctzya55.

Editing the Code in Your Theme THEME