Custom Post Types are arguably the feature that brought WordPress from being a standard blogging application up to a CMS. I’d even go as far to say that this feature also added new APIs for developers to use when building web applications.

Custom Post Types

Here’s a post, but this isn’t exactly representative of a custom post type.

Though posts, pages, and basically anything that as a title and the editor (among other optional features) are post types, custom post types are what allow us to actually create a model of information to store in the database, associated with metadata, and more.

The point of this post isn’t about how great custom post types are, though. Instead. it’s about how to handle the case whenever you receive the following message:

Fatal error: Call to a member function add_rewrite_tag() on a non-object

Fatal error? That’s never good. The nice thing is that this isn’t really terribly difficult to fix.

Register Custom Post Types

To make sure we’re all on the same page, here’s a quick example of the code that’s used to register custom post types (well, in this case, a single custom post type):

Easy enough to understand, right? And there’s plenty of explanation for this in the Codex. I also have a demo available for how to set up a generic custom post type that’s bundled in a plugin.

But here’s the thing: If you’re doing this within the context of a plugin, then you’re likely dealing with hooks.

And if you’re not familiar with the order in which hooks fire, then you may end up seeing the error above message. If that’s the case, then you can be almost certain you’re not registering your custom post types at the proper time.

There’s a Time For This

What does that mean, though? If you’re not familiar with how hooks, the WordPress lifecycle, and so on work then you can review this page (and I have some articles about this coming out in the future).

In the meantime, though, it’s important to understand that there are certain parts of the WordPress application are available at certain times. If you try to register something too early, like custom post types, then you end up getting errors when a dependent function (like add_rewrite_tag() fires.

The fix for this problem is simple:

Make sure that you register your custom post types during or after the init hook fires. Otherwise, you’ll end up without an object that add_rewrite_tag() requires to complete its task.

Straightforward, right? But this is important to know so that we’re able to properly register our custom post types without having to deal, debug, and trace cryptic fatal errors (which sound like a bigger deal than they really are).