WordPress: Add a custom type with custom fields

If you’ve used any system that allows for custom fields / custom entities, you may find the WordPress system quite alien (e.g.: compare to SalesForce, Documentum, SharePoint etc).

Like most tools, the WordPress customization model is typically a mix of configuration, code, and plugins, but since you can edit any code, anywhere in the system, you have to be a little careful (there is no notion of “versioning” the database, that I can see, for instance, so how to do migrations is an open question).

Typically any piece of code you’d write yourself (e.g. adding a custom type) can be extracted and made into a plugin. Thus, part of customizing WordPress is a trade-off between deciding what to customize yourself and what to delegate to existing plugins.

For adding a custom type, for instance, it’s pretty easy to just drop in some code:


add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'error_message',
    array(
      'labels' => array(
        'name' => __( 'Errors' ),
        'singular_name' => __( 'Error' )
      ),
      'public' => true,
      'has_archive' => true,
    )
  );
}

This does start to show where some of the pain is going to come in – every attribute we add has to have labels for every action, which isn’t much fun to do.

You can add custom fields as key-value stores, but they are hard to maintain and don’t support any complex value assistance behaviors.

Consequently, the best thing to do is to install a plugin (“Advanced Custom Fields”) that manages this for you.

Here, I’ve set up a custom field group for a section of my blog (“error messages from popular javascript libraries”). In my setup, each custom field is an attribute of an error message:

When you set this up, you have a fair amount of configuration options – you can make it a preset list of values, and make it conditional upon other fields:

The fields show up on the “new post” screen the way you’d expect:

Now that you’ve done this, you have custom fields. In future posts I’m going to investigate how to handle migrating changes (as an application grows), moving data from server to server, and other issues involved maintaining such a site.

Leave a Reply

Your email address will not be published. Required fields are marked *