Registering Custom Post Types

Registering Custom Post Types is a breeze, really. You just need to set all the variables that are going to govern how your custom post type should function, and put that code in either a plugin, or your theme, depending on which is more appropriate (it’s usually going to be a plugin by the way, even if you need to create a new one).

The Codex has a very helpful article on the subject, and I’m going to walk you through it with an example to show how versatile it is. In my example, I created an order tracking system for one of my clients, and as you can see from the screenshot below, custom post types don’t have to look anything like a regular post; you can tailor them to your every need.

The dashboard view of a custom post type can be set to look however you need.

The code behind it

In order to register a custom post type, you need to use the register_post_type function. Here is the code that I used to build the order system shown above:

So, first thing to note is that the custom post type name is hbos_orders. That can be seen in register_post_type function near the bottom of the code. Everything above that is setting the variables that determine how the post type should function. For example, you can set all the terminology that will be used for the post type when they’re viewed in the dashboard and on the site (such as View Order, Edit Order and Add New Order). You can also set whether the post type should have it’s own dashboard menu, whether is should be searchable, viewable by the public, have archives and whether you should be able to create a hierarchy structure (create parent and child items).

The supports argument is useful, because you can dictate what elements of the normal post editing window should be permitted on your post type. In this example, I’ve only allowed the title, author, and revisions, which means that the tag window, category window, post thumbnail box and even the editor window will not be shown – this is because I am using custom meta boxes to save the information I want to use.

The example above only contains some of the variables that you can set, so I strongly recommend that you check out the Codex article to see what other variables you can add to set up your own custom post type.

One last thing that you’ll want to do is flush the rewrite rules, but only once the plugin is activated (flushing rewrite rules is very server intensive and should not be do on every page load, on init, or admin_init for example). To do so, add a function like this below your function that registers the custom post type:

And that’s the basics for registering a custom post type. What you do with it beyond that is really up to you: I’d be interested to hear what interesting tasks you’re using them to do.

Leave a Reply