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.

Advertisements
Defining a Custom Post Type with a Plug-In

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