Custom Post Types

Last night I gave a presentation at the WordPress London meetup. I talked about custom post types in WordPress, something that has really excited me since WordPress 3. I’ve included the video, a rough transcript of the presentation and the slides at the bottom.

What we’ll cover

  • What are custom post types
  • When to use them
  • How to use custom post types
  • Taking things further
  • Resources

What are custom post types?

I’ve searched high and low on the internet for a decent definition of custom post types, with no luck. The best that I’ve seen is that they are really custom content types.

Replacing the word ‘posts’ with ‘content’ gives us a much better understanding of what custom post types are all about. The idea is that there is some content on your website that might not fit neatly into the typical page’ or ‘post’ mould. Think of the following examples:

  • Movies
  • Staff
  • Podcasts
  • Books
  • Products
  • Portfolio items
  • Testimonials, etc, etc.

Then why are they called custom post types?

Within WordPress there are already various post types: posts, pages, menus and revisions. With version 2.9 came the ability to define your own, ‘custom’, post type. These are stored in the wp_posts table. Hence custom post types.

When to use custom post types

Here is a fairly typical client request:

“I want to create a website for my holiday home rentals company. I have a portfolio of 20 properties that I want to be able to manage and update. Each property has the following information:

  • Name
  • Address
  • Short intro
  • Full property description
  • An image
  • Price per week
  • Number of rooms

I would like the user to able to sort the properties by ‘Price’ and ‘Number of rooms. I will also be blogging on the site.”

Without custom post types

In those dark days before WP 2.9 I probably would have used posts for the properties. I then would have created a category of ‘properties’ so that I could style those property posts differently than the regular blog posts. I then would have used custom fields for the meta data – rooms and price.

This used to work, but it was an ugly solution, a ‘hack’. The property posts would be mixed in with the regular blog posts both in the admin and the front-end.

Enter, custom post types

With custom post types we can separate our content into logical groups. Posts are now just chronological blog/news items again and properties have their own section.

This also makes theme development easier. The posts and properties are no longer lumped together, so no need to hack the index.php loop. New templates are available specifically for your properties post type too.

Basically, using custom post types is going to seriously improve workflow for both you and your client.

How to use custom post types

Creating your custom post type

Before I start, I have to tell you that there are ways to create custom post types on your WordPress site without having to touch a single line of code. There are several plugins and online code generators that will do it all for you. However, I strongly encourage you to have a go at this yourself. Even if this is the first bit of theme development that you have done, give it a go. You’ll have a much better idea of what’s going on and you’ll find it so satisfying.

Open up your theme’s functions.php file using your favourite text editor, and add the following:

[php]

add_action( ‘init’, ‘create_my_post_types’ );

function create_my_post_types() {
register_post_type( ‘kdev_properties’,
array(
‘labels’ => array(
‘name’ => __( ‘Properties’ ),
‘singular_name’ => __( ‘Property’ )
),
‘public’ => true,
‘has_archive’ => true,
‘supports’ => array(‘title’,’editor’,’excerpt’,’thumbnail’),
‘rewrite’ => array( ‘slug’ => ‘property’ ),
‘register_meta_box_cb’ => ‘add_property_metaboxes’,

)
);
}

[/php]

This code is all we need to get custom post types working on our WordPress site. in fact, it’s more than we need, I’ve added a few lines, 11, 13 and 14, that aren’t essential but useful for what we’re trying to achieve.

Line 4 is where the magic starts, we’re registering our post type and giving it a name. I’ve prefixed the name with ‘kdev_’ to avoid clashes with any other plugins.

Line 6 starts the ‘labels’ array and at this point we’re only using two labels ‘name’ and ‘singular_name’. These will appear in our theme instead of the ugly ‘kdev_properties’. There are lots more labelling options, check them out here http://codex.wordpress.org/Function_Reference/register_post_type#Arguments.

Line 10 is telling WordPress to make the post type public, that is visible, in the admin and front-end. Strangely this defaults to false, so you must include it if you want to see your post type.

‘has_archive’ on line 11 is optional. I’m using it to tell WordPress that I will be using a custom archive template.

The ‘supports’ array on line 12 is where it starts to get interesting. Everything that you are familiar with from posts and pages are available to you here. I’m just enabling the elements that we’ll need for our property post type.

Line 13 enables a URL rewrite. This changes our URL structure from kdev_properties/propertyname to property/propertyname (assuming we’re using a ‘pretty’ permalink structure).

The last line, 14, is telling WordPress that I wish to use a custom meta box on this post type. this will be explained in greater detail later on.

Now log in to your WordPress admin area and you should see something similar to the following:

You can see that our custom post type, ‘properties’, has been added to the main menu, keeping it separate from posts and pages.

If you click on the ‘Properties’ link and then ‘Add New’ you will get to the following screen.

Here we can see the ‘supports’ array in action. We’ve added some useful functionality here but it’s also important to note what we’ve left out. The categories and tags that we are familiar with from posts are gone, as are page attributes, revisions, comments and discussions. This leaves us with a nice clean UI. There are no extraneous admin elements to distract the user.

Our code hasn’t just created a great admin screen, it’s also enabled us to view our custom post type live on the site. From the ‘Edit Post’ screen, click on ‘Preview’ to see what your post will look like (add some content first for a better effect!). You’ll see something like this:

That’s great so far, but the chances are that you’ll want your custom post type to look slightly different to regular posts. WordPress gives us two template files to do this; single-[posttype].php and archive-[posttype].php.

The single template will let you style your individual custom post types, in our case the single property page. It’s often easiest just to create the new template file (e.g. single-kdev_properties.php), in your theme directory, and copy and paste the code from your theme’s single.php file. Then you can make any changes that you require. Before you do that though, there are some more tricks that will help you make your custom post type really come to life!

The archive-[posttype].php template will create a page that displays a list of your custom posts. Using the same idea as above, you can copy and paste from your index.php file and edit from there. Remember the ‘has_archive’ argument that we added? That line is telling WordPress to use our custom archive file.

Congratulations! You’ve created your first custom post type. That wasn’t too hard was it? There is loads more that we can do with our custom post type.

Taking things further

Remember the original client request? She wanted to be able to add ‘price’ and ‘number of rooms’ data to her properties. Of course, we could just add this to the main text editor, but then it would be tricky to separate the data if we wanted to use it by itself. This is where custom meta boxes come in.

Custom meta boxes

Here’s where custom post types start to get really cool. We’re not limited to the ‘title’, ‘excerpt’, etc. that WordPress provides us with. We can add new boxes to our edit screen that accept any kind of data that we can think of.

Here’s an example of some meta boxes:

The first meta box is a simple text field, the second a radio button. You could have checkboxes, text-areas, TinyMCEs, etc. By now your imagination should be kicking in to show you the possibilities available!

We want two meta boxes, one for price and one for rooms. Here’s the code that we need to achieve this:

[php]

//Add custom meta box

// Add the Properties Meta Boxes

function add_property_metaboxes() {
add_meta_box(‘kdev_properties_rooms’, ‘Number of Rooms’, ‘kdev_properties_rooms’, ‘kdev_properties’, ‘side’, ‘default’);
add_meta_box(‘kdev_properties_price’, ‘Price per week’, ‘kdev_properties_price’, ‘kdev_properties’, ‘side’, ‘default’);
}

// Output the Property metaboxes

function kdev_properties_rooms() {
global $post;

$prop_rooms = get_post_meta($post->ID, ‘_rooms’, true);

echo ‘<label>Rooms</label><input class=”widefat” name=”_rooms” type=”text” value=”‘ . $prop_rooms . ‘” />’;
}

function kdev_properties_price() {
global $post;

$prop_price = get_post_meta($post->ID, ‘_price’, true);

echo ‘<label>Price per week</label><input class=”widefat” name=”_price” type=”text” value=”‘ . $prop_price . ‘” />’;
}

// Save the Metabox Data

function kdev_save_property_meta($post_id, $post) {
if ( ‘kdev_properties’ == get_post_type() ) {

if ( !current_user_can( ‘edit_post’ , $post ->ID )) return $post ->ID;

$property_meta[‘_rooms’] = $_POST[‘_rooms’];
$property_meta[‘_price’] = $_POST[‘_price’];

foreach ($property_meta as $key => $value) { // Cycle through the $property_meta array!
if( $post->post_type == ‘revision’ ) return; // Don’t store custom data twice
$value = implode(‘,’, (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn’t have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}
}

add_action(‘save_post’, ‘kdev_save_property_meta’, 1, 2); // save the custom fields
[/php]

This is a bit more complex and I won’t go through every line. Add this to your functions.php file and make sure that the variable names are correct (if you have used something other than ‘kdev_properties you’ll need to change it here too).

There are some arguments that you may wish to tinker with. Remember, you won’t learn if you don’t make mistakes, so don’t be scared. It’s always a good idea to make backups before you start experimenting though, especially with a live site.

Adding that code will give you something like this:

Check out those custom meta boxes on the right! Sweet.

As cool as it is to have custom meta boxes, they’re not going to do anything for you without a bit of work to your template files.

Open up one of your custom template files and add the following:

[php]

Price per week: £<!–?php echo get_post_meta(get_the_ID(), ‘_price’, true); ?–>

Number of rooms: <!–?php echo get_post_meta(get_the_ID(), ‘_rooms’, true); ?–>

[/php]

The get_post_meta() function is creating all the magic here. It takes a few arguments, the post ID, the meta key, and whether to return a single string or an array (‘true’ will return the string).

I’ve added those lines to my custom archive template to get the following:

Nice work. Our custom post types have meta boxes and we have some pretty nifty templates. There’s one more part to the holy trinity of custom awesomeness…

Custom taxonomies

Taxonomies are ways to classify your data. If you’re familiar with WordPress you will already be using them; categories and tags. These are both taxonomies, but they are very general, and you’ll probably want to keep these for your blog posts.

For our custom post types we can create our own custom taxonomies. There are two main types; hierarchical and, erm, not.

Hierarchical taxonomies

Hierarchical taxonomies have the concept of parents and children, like categories. You can create tree like structures of nested classifications.

Non-hierarchical taxonomies

These are like post tags. They don’t have parents or children.

Creating a custom taxonomy

[php]
function my_register_taxonomies() {

register_taxonomy(
‘area’,
array( ‘kdev_properties’ ),
array(
‘public’ => true,
‘labels’ => array( ‘name’ => ‘Area’, ‘singular_name’ => ‘Area’ ),
‘hierarchical’ => true,
)
);
}

add_action( ‘init’, ‘my_register_taxonomies’ );
[/php]

This is all we need to create a custom taxonomy for our custom post type. I’ve given it a name, assigned it to the ‘kdev_properties’ post type and given it some arguments. Again, have a play around. The code can be added to your functions.php file as before.

And so we have it. Well done for getting to the end!

Hopefully, you’ll be inspired to use custom post types on your next project. You’ll never look back, I promise.

Resources

http://codex.wordpress.org/Post_Types
http://codex.wordpress.org/Function_Reference/register_post_type

Plugins

http://wordpress.org/extend/plugins/custom-post-type-ui/
http://wordpress.org/extend/plugins/custom-content-type-manager/

Posts

http://justintadlock.com/archives/2010/04/29/custom-post-types-in-wordpress
http://devpress.com/blog/conditional-checks-for-custom-post-types/
http://css-tricks.com/forums/discussion/8538/wordpress-3.0-custom-post-types-and-meta-boxes/

Easy meta boxes with WPAlchemy

http://www.farinspace.com/wpalchemy-metabox/

The slides

 

One response to “Custom Post Types”

  1. Andrew Bailey Avatar

    great post. I made a plugin with custom post types when they first came out for a restaurant order system and wanted to see if anything has changed, seems like there hasn’t!

    good work on making this post easy to read. thanks!

Leave a Reply

Your email address will not be published.