Up and Running With Custom Post Types

Apr 5, 2012
WordPress
By

If you’re reading this post, chances are you’re familiar with WordPress and its role in the web world as a blogging platform, content management system, multisite administrator, and much more.

While WordPress can be a viable solution for any small business website or blog right out of the box from a fresh install, you can harness the true value of WP by diving into the code and creating Custom Post Types.

What Is A Custom Post Type?

WordPress ships with two default post types, Posts and Pages. By default, posts are time sensitive articles with a certain shelf live. Pages are more evergreen material, designed to remain fairly static such as an About page or Contact page.

A Custom Post Type adds a third (or fourth, or fifth, etc.) type of post to your WordPress sites. For example, I recently completed a site for a local indoor club field hockey team. For their site, I created an athlete profile for every player as a custom post type. This type, similar to user account, collects information on the athletes including academic, athletic and personal information and outputs that on a profile page.

Custom Post Types can be as simple or robust as you’d like. That is what makes it one of the most powerful features in WordPress. With some lines of code in functions.php, you can get up and running with Custom Post Types in your WordPress Themes.

Wait. I have to code? Aren’t there plugins for this?

You betcha. But, I would advise against it. Other than the fact that you’re reading this on Developer Drive and we would obviously rather code it than use a plugin, by coding your Custom Post Type directly, you maintain complete control over what data you collect, where it goes, how you display it, and much more. Plus, if you continue adding plugin after plugin, you’re going to seriously hamper the performance of the site. Don’t waste a plugin on post types.

How is this tutorial going to work?

This is my first tutorial on Developer Drive, so I might go through things a little differently than others that you’ve read before (or could be exactly the same). I will always explain what we’re doing, why we’re doing it, and then show you the code for it. I think the human mind flows best when it has an idea of what it’s looking at and trying to digest.

With that in mind, let’s get started creating a custom post type.

Getting Started

To start, you will probably want to have a fresh install of WordPress on a local server (read up on how to set up a local installation with MAMP or WAMP) and a code editor. It also helps if you’re familiar with WordPress, at least to some degree, and know the role of the functions.php file.

A tip that I’ve gleaned from other developers is to maintain portability with your code, and it is this reason why I suggest when starting your custom post type, you do so in a separate .php file and include it in your functions.php. This keeps functions.php readable, and allows you to take the custom post type from site to site.

So go ahead and open up your code editor, open your themes functions.php file, and create a new .php file.

Registering The Custom Post Type

The first thing we’ll want to do is register the custom post type in our .php file, and then include it to functions.php. For more detailed information on registering your custom post type, take a peak at the WordPress Codex topic on register_post_type();. We first call our add_action() function with init and referencing our function name.

Once we’re initialized, we create two arrays called $labels and $args. These will create the labels you see in the Admin area, as well as the slug for the permalinks (if you use a pretty permalink setting).

Finally, after declaring the $lables and $args, we register the post type with register_post_type();. Here’s the code we have so far.

add_action('init', 'athlete_register');

function athlete_register() {

	$labels = array(
		'name' => _x('Athlete Profiles', 'post type general name'),
		'singular_name' => _x('Athlete Profile', 'post type singular name'),
		'add_new' => _x('Add New', 'athlete profile'),
		'add_new_item' => __('Add New Athlete Profile'),
		'edit_item' => __('Edit Athlete Profile'),
		'new_item' => __('New Athlete Profile'),
		'view_item' => __('View Athlete Profile'),
		'search_items' => __('Search Athlete Profiles'),
		'not_found' =>  __('Nothing found'),
		'not_found_in_trash' => __('Nothing found in Trash'),
		'parent_item_colon' => ''
	);

	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'query_var' => true,
		'menu_icon' => null,
		'rewrite' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array('title','editor','thumbnail')
	  ); 

	register_post_type( 'athlete' , $args );
}

As I mentioned before, take a look at the WordPress Codex for in-depth descriptions on what various arguments you can pass for $labels and $args.

Now let’s hop over to our theme’s functions.php and include our custom post type .php file. This is the magic that actually makes it appear in your admin area.

// Add the Custom Post Type
	require_once('_/inc/athleteprofile.php');

As you can see from that link of code, my custom post type file is called athleteprofile.php and is in my includes folder. Head back to your WordPress admin, click refresh and low and behold! We have a custom post type!

Granted, it doesn’t do a whole lot yet. But that will change soon.

In part two of our post on Custom Post Types, we’ll cover creating Taxonomies to categorize your new posts by, create custom fields and meta boxes, saving your Custom Post Type data to the WordPress database, and using your fields in your theme.

Author: Alex Ball
Alex has been working in web design and development for over five years, and loves learning and expanding his skill set. A fan of CSS3 and HTML5, he also enjoys going old school with HTML (table) Emails.
  • http://www.paulund.co.uk/ Paul

    Nice article, I agree it’s always better to code your own plugins than to download one.

  • http://www.facebook.com/amigosdios Allar Pani

    When can we expect part 2 of this tutorial?

    • http://twitter.com/AlexBall12 Alex Ball

      Part two is complete and ready to roll. Should be posted in the next week or so, depending on the other articles already scheduled! But definitely keep an eye out!

      • http://www.facebook.com/amigosdios Allar Pani

        Thanks for the quick response, i’ll keep my eyes open for this one.

  • http://twitter.com/AlexBall12 Alex Ball

    Absolutely, I’ve got some images and usage in themes coming in Part 2 of the post, then I’m also here for any questions on the topic!

  • http://www.facebook.com/cliftonc Clifton Canady

    I love this article. I like how you explain everything and then give the code. I’m a visual person and that helps out a lot.

    Thanks

  • http://thenextlab.com/ Steven

    Always wondered hot to create it by myself as currently I am using plugin for this purpose but I believe it’s better to keep numbers of plugins down so the site doesn’t get too slow.
    Thanks Alex for tutorial!

  • http://www.facebook.com/victorcachay Victor Cachay

    Good article, very didactic. I hope the second part

  • Elvedonstreet

    Hanging out for part 2!

  • http://twitter.com/MikeStvnsn Mike Stevenson

    Great! When is part 2 going to be released?

  • jeff_DD

    Part 2 will be coming next week! Check back on tuesday…

  • http://www.facebook.com/amigosdios Allar Pani

    Up, but not running. Still waiting for the part 2 of this tutorial or am I blind for not seeing it?

    • jeff_DD

      It is scheduled and will be posted soon.

      • http://www.facebook.com/amigosdios Allar Pani

        I sure hope so, it’s two months since the first part.

  • http://twitter.com/thomasgerard86 thomasgerard

    These
    are really nice blogs. i will gonna look at them! thanks for the resource
    here!