A developer’s life beyond the screen.


Dev Tip #5: Creating Custom Post Types (The Right Way)

Custom Post Types (CPTs) are one of the most powerful features in WordPress.
But if you’ve ever seen “badly done” CPTs, you know they can cause more pain than progress.

Here’s how I register Custom Post Types the clean and reliable way in plugins.


1. Use init, Not plugins_loaded

Always hook your CPT registration to init, not plugins_loaded.

add_action( 'init', 'my_plugin_register_post_type' );

function my_plugin_register_post_type() {
    register_post_type( 'book', [
        'labels' => [
            'name'          => __( 'Books', 'my-plugin' ),
            'singular_name' => __( 'Book', 'my-plugin' ),
        ],
        'public'       => true,
        'has_archive'  => true,
        'rewrite'      => [ 'slug' => 'books' ],
        'show_in_rest' => true, // Important for block editor support
        'supports'     => [ 'title', 'editor', 'thumbnail' ],
    ]);
}

2. Use flush_rewrite_rules() Correctly

Don’t flush rewrite rules on every page load.
Do it only on plugin activation.

register_activation_hook( __FILE__, 'my_plugin_activate' );

function my_plugin_activate() {
    my_plugin_register_post_type(); // Ensure it's available before flushing
    flush_rewrite_rules();
}

3. Don’t Forget show_in_rest

If you’re using Gutenberg or REST API, set:

'show_in_rest' => true

It enables block editing, custom fields via REST, and plays nicer with modern tools.


4. Use textdomain in Labels

Don’t hardcode English. Use __() or _x() with your plugin’s text domain so it’s translatable.

'name' => __( 'Books', 'my-plugin' )

5. Don’t Abuse CPTs

Don’t create a CPT when a taxonomy or custom fields would work better.
For example: if it doesn’t need its own archive, slug, or UI — maybe it’s just metadata.


Final Thought

CPTs are easy to register — but easy to overuse too.
Keep them clean, REST-ready, and only when needed.

A good rule of thumb?
“If this was a SaaS product, would this content type deserve its own section?”


Comments

Leave a Reply

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