WordPress Custom Post Types: How to Create and Use Them (with Code)

A custom post type (CPT) is a new content type you add to WordPress alongside Posts and Pages: portfolio items, events, recipes, properties, anything that needs its own admin menu, its own fields, and its own URLs. You create one by calling register_post_type() on the init hook (in a small plugin or functions.php), or with a plugin like Custom Post Type UI or ACF if you would rather not write code.

This guide covers the code, every $args option that matters (with its real default from core), how to show CPT entries on the front end, the template files WordPress looks for, and which plugin to pick. The registration code below was run on WordPress 7.1.4 in WordPress Playground, including the 20-character key limit and the 404-before-flush behavior.

Key Takeaways
  • A custom post type (CPT) is a content type beyond the default Posts and Pages, like products, portfolios, or events, registered with register_post_type().
  • Register CPTs in a small custom plugin (not your theme’s functions.php) so they survive a theme switch.
  • Set 'show_in_rest' => true so the CPT works in the block editor and the REST API.
  • After registering a CPT, flush rewrite rules once (Settings > Permalinks, or flush_rewrite_rules() on plugin activation) or its URLs will 404. Never flush on every init.
  • Prefer a no-code route? CPT UI, the free version of ACF (since 6.1), and Pods all register CPTs through a UI.

What Are Custom Post Types?

Every piece of content in WordPress is a row in the wp_posts table, and the post_type column says what kind of content it is. Blog posts have post, pages have page, images have attachment. A custom post type is a new value for that column plus a registration that tells WordPress what admin UI to render, what URLs to use, which taxonomies apply, and which editor features to show. No extra database table is involved.

WooCommerce products are a CPT (product). So are Elementor templates, Contact Form 7 forms, and ACF field groups. Once a type is registered, the block editor, REST API, admin list tables, template hierarchy, search, and archives all treat it as a real content type.

Default post types in WordPress

Calling get_post_types( array( '_builtin' => true ) ) on a fresh WordPress 7.1.4 install returns 16 built-in post types. Only the first five show up as content most people think about; the rest are internal storage for the Customizer, oEmbed, privacy requests, and the Site Editor.

Post type keyWhat it stores
postBlog posts
pagePages
attachmentMedia library items
revisionSaved revisions of other posts
nav_menu_itemClassic menu items
custom_cssAdditional CSS from the Customizer
customize_changesetUnpublished Customizer changes
oembed_cacheCached oEmbed responses
user_requestPersonal data export and erasure requests
wp_blockSynced patterns (formerly reusable blocks)
wp_template, wp_template_partBlock theme templates and template parts edited in the Site Editor
wp_global_stylesGlobal Styles saved in the Site Editor
wp_navigationNavigation block menus
wp_font_family, wp_font_faceFonts installed through the Font Library
Built-in post types returned by get_post_types() on WordPress 7.1.4.

When to Use a Custom Post Type (and When to Skip)

Custom post types are the right answer when:

  • The content has its own editorial schema. Portfolio items have a client, a date, and a gallery. Events have a venue and a start time. Recipes have ingredients and instructions.
  • Editors should see it as its own admin menu (“Portfolio”, “Events”) instead of mixed into Posts.
  • You want URL separation. yoursite.com/events/wordcamp-2026/ reads cleaner than yoursite.com/2026/01/wordcamp-2026/ and gets its own archive page.
  • You are building for headless WordPress. CPTs are how you model the content your frontend consumes, instead of using categories as a type discriminator on Posts.

Skip CPTs and use regular Posts when:

  • The content is editorially identical to your blog posts. If “Articles” and “News” are both just articles with a different label, use a category.
  • You would only have a handful of entries. A CPT for five items is not earning its complexity.
  • The difference is purely visual (a different layout) rather than structural (different fields). A custom template or block pattern handles that.

How to Create a Custom Post Type with register_post_type()

register_post_type() takes two arguments: the post type key and an array of options. This is a complete, working registration. Put it in a small plugin file in /wp-content/plugins/ (or your theme’s functions.php for a quick test):

add_action( 'init', 'smartwp_register_portfolio_cpt' );

function smartwp_register_portfolio_cpt() {
    register_post_type( 'portfolio', array(
        'label'        => 'Portfolio',
        'public'       => true,
        'has_archive'  => true,
        'show_in_rest' => true,
        'supports'     => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
        'menu_icon'    => 'dashicons-portfolio',
        'rewrite'      => array( 'slug' => 'portfolio' ),
    ) );
}

That gives you a “Portfolio” admin menu, an archive at yoursite.com/portfolio/, single items at yoursite.com/portfolio/item-slug/, the block editor, and REST endpoints at /wp-json/wp/v2/portfolio. On a 7.1.4 test install, the archive and the first item both returned 404 until rewrite rules were flushed, then 200 (more on that in the permalinks section).

Three rules from the official docs that trip people up:

  • Hook it on init. The core docblock says registrations “should not be hooked before the ‘init’ action,” and the Plugin Handbook says to call it after after_setup_theme and before admin_init.
  • Keep the key at 20 characters or less. The post_type column is VARCHAR(20). A 21-character key does not register: register_post_type() returns a WP_Error with the code post_type_length_invalid and the notice “Post type names must be between 1 and 20 characters in length.”
  • Use lowercase letters, numbers, dashes, and underscores only (the key runs through sanitize_key()), never start it with wp_, and prefix generic names. The handbook’s example is wporg_product, because a bare product collides with WooCommerce.

register_post_type() Arguments That Matter

The defaults below come from the WP_Post_Type class in WordPress 7.1.4. Several options inherit from public, so setting 'public' => true flips a handful of them at once. The full list lives in the register_post_type() reference.

ArgumentDefaultWhat it does
label / labelsInherited from Posts (or Pages if hierarchical)label is the menu name. labels is an array of UI strings (add_new_item, edit_item, not_found, and so on); set at least name and singular_name or the admin says “Add Post”.
publicfalseMaster switch. Sets the defaults for show_ui, publicly_queryable, exclude_from_search, and show_in_nav_menus.
show_in_restfalseAdds REST routes and is required for the block editor. Leave it off and the CPT gets the classic editor and no /wp/v2/ route.
supportsarray( 'title', 'editor' )Editor features to enable (list below). Pass false for none.
has_archivefalsetrue creates an archive at the rewrite slug. A string sets a different archive slug, e.g. 'has_archive' => 'work'.
rewritetrue (slug = key)Array with slug, with_front (default true), feeds (defaults to has_archive), pages. false turns off pretty URLs.
hierarchicalfalseParent/child entries like Pages. Use page-attributes in supports to get the Parent dropdown.
menu_iconPosts iconA Dashicons class like dashicons-portfolio (see the Dashicons list), a data:image/svg+xml;base64, SVG that picks up the admin color scheme, or 'none' to style it with CSS.
menu_positionnull (bottom)Core menu slots: 5 Posts, 10 Media, 20 Pages, 25 Comments, 60 Appearance, 65 Plugins, 70 Users, 75 Tools, 80 Settings. Use 6 to sit right under Posts.
taxonomiesEmpty arrayTaxonomies to attach, e.g. array( 'category' ) or your own. The docs recommend attaching them here rather than later.
capability_type / map_meta_cap'post' / falseBase for edit/delete capabilities. Set a custom string plus 'map_meta_cap' => true to give the CPT its own permissions.
rest_baseThe keyChanges the REST route, e.g. /wp/v2/projects.
template / template_lockEmpty / falseStarting blocks for new entries in the block editor. template_lock can be 'all', 'insert', or 'contentOnly'.
delete_with_usernullWhen null, entries are trashed with their author only if the CPT supports author.
register_post_type() arguments and their defaults in WordPress 7.1.4.

Block editor templates for a CPT

The template argument pre-fills every new entry with blocks, which keeps editors on a consistent structure. This is different from a theme template file: it controls the editor, not the front end.

register_post_type( 'portfolio', array(
    'public'        => true,
    'show_in_rest'  => true, // template only applies in the block editor
    'template'      => array(
        array( 'core/image' ),
        array( 'core/heading', array( 'placeholder' => 'Project summary' ) ),
        array( 'core/paragraph', array( 'placeholder' => 'What you built and why' ) ),
    ),
    'template_lock' => 'insert', // can move blocks, cannot add or remove them
) );

The supports Array: What Each Feature Does

If you leave supports out, WordPress gives you title and editor. Adding editor also turns on autosave (on the test install, a CPT registered with no supports reported title, editor, autosave). Core features:

  • title: the title field.
  • editor: the content editor (block editor if show_in_rest is true, classic otherwise).
  • thumbnail: featured image (the theme must also support post-thumbnails).
  • excerpt: the manual excerpt field.
  • author: the author selector.
  • comments: comments and the comment count on the edit screen.
  • revisions: stores revisions.
  • custom-fields: the custom fields panel. Also needed if you register post meta with 'show_in_rest' => true for this CPT.
  • page-attributes: menu order, plus the Parent dropdown when 'hierarchical' => true.
  • post-formats: post format support.
  • trackbacks: trackbacks and pingbacks.

For a typical portfolio or event CPT, array( 'title', 'editor', 'thumbnail', 'excerpt' ) is enough.

Custom Taxonomies for CPTs

Categories and Tags belong to Posts. For a CPT you usually want your own: portfolio “Skills”, event “Locations”. Register them with register_taxonomy():

add_action( 'init', 'smartwp_register_portfolio_taxonomies' );

function smartwp_register_portfolio_taxonomies() {
    register_taxonomy( 'skill', 'portfolio', array(
        'label'        => 'Skills',
        'public'       => true,
        'hierarchical' => false,
        'show_in_rest' => true,
        'rewrite'      => array( 'slug' => 'skill' ),
    ) );
}

That adds a “Skills” taxonomy to the portfolio CPT with its own admin screen, REST route, and term archives at yoursite.com/skill/php/. 'hierarchical' => true makes it behave like categories (checkboxes, parents); false makes it behave like tags. Set show_in_rest on the taxonomy too, or its panel will not appear in the block editor.

How to Display Custom Post Type Posts (WP_Query Loop)

With has_archive on, WordPress already lists entries at /portfolio/. To show them anywhere else (a homepage section, a sidebar, a shortcode), run a custom WP_Query with post_type:

$portfolio = new WP_Query( array(
    'post_type'      => 'portfolio',
    'posts_per_page' => 6,
    'orderby'        => 'date',
    'order'          => 'DESC',
) );

if ( $portfolio->have_posts() ) {
    echo '<ul class="portfolio-list">';
    while ( $portfolio->have_posts() ) {
        $portfolio->the_post();
        printf(
            '<li><a href="%s">%s</a></li>',
            esc_url( get_permalink() ),
            esc_html( get_the_title() )
        );
    }
    echo '</ul>';
    wp_reset_postdata();
}

Always call wp_reset_postdata() after a custom loop so the rest of the template gets the main query’s post back. To filter entries by a field value (events after today, properties under a price), add a meta_query to the same arguments, and read the values inside the loop with get_post_meta().

On a block theme you do not need PHP for this: add a Query Loop block, open its settings, and pick your CPT under Post type. That option only lists post types registered with 'show_in_rest' => true.

To change the archive itself (say, 24 items per page or alphabetical order), modify the main query with pre_get_posts instead of running a second query:

add_action( 'pre_get_posts', function ( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_post_type_archive( 'portfolio' ) ) {
        $query->set( 'posts_per_page', 24 );
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
    }
} );

Exposing CPTs to the REST API

'show_in_rest' => true does two things: it exposes the CPT in the WordPress REST API at /wp-json/wp/v2/{rest_base}, and it enables the block editor. Core’s use_block_editor_for_post_type() returns false if the type lacks editor support or has show_in_rest off. On the test install, the portfolio route returned 200 while a CPT registered without show_in_rest returned 404 (rest_no_route).

The REST base defaults to the CPT key. Change it with rest_base:

register_post_type( 'portfolio', array(
    'public'       => true,
    'show_in_rest' => true,
    'rest_base'    => 'projects',  // /wp-json/wp/v2/projects instead of /wp-json/wp/v2/portfolio
    // ...other args
) );

For headless builds, show_in_rest is required: the frontend has to fetch CPT entries over REST or WPGraphQL.

A public CPT gets its own rewrite rules, but WordPress stores rules in the rewrite_rules option and does not rebuild them on its own when you add a new type. That is why a freshly registered CPT 404s. The rewrite argument shapes the URLs:

  • 'slug' => 'portfolio' sets the prefix: yoursite.com/portfolio/sample-project/.
  • 'with_front' => false ignores the static front of your permalink structure (for example, the /blog/ in /blog/%postname%/).
  • 'feeds' => true builds a feed at yoursite.com/portfolio/feed/ (on by default when has_archive is true).

To fix the 404 by hand, go to Settings > Permalinks and click Save Changes, or run wp rewrite flush with WP-CLI. In a plugin, flush once on activation, after registering the CPT. This is the pattern from the Plugin Handbook:

register_activation_hook( __FILE__, 'smartwp_portfolio_activate' );

function smartwp_portfolio_activate() {
    smartwp_register_portfolio_cpt(); // register first, so its rules exist
    flush_rewrite_rules();
}

register_deactivation_hook( __FILE__, 'smartwp_portfolio_deactivate' );

function smartwp_portfolio_deactivate() {
    unregister_post_type( 'portfolio' );
    flush_rewrite_rules();
}

Do not put flush_rewrite_rules() inside your init callback. The function reference calls it “an expensive operation” that “should only be used when necessary,” and on init it would rebuild every rule on every page load.

Template Files for Custom Post Types

The template hierarchy picks up CPT templates by file name; you do not register them. For a classic (PHP) theme, WordPress checks these in order, per core’s get_single_template() and get_archive_template():

RequestClassic theme (PHP)Block theme (/templates/)
One portfolio itemsingle-portfolio-{slug}.php, single-portfolio.php, single.php, singular.php, index.phpsingle-portfolio-{slug}.html, single-portfolio.html, single.html, singular.html, index.html
Portfolio archivearchive-portfolio.php, archive.php, index.phparchive-portfolio.html, archive.html, index.html
Skill term archivetaxonomy-skill-{term}.php, taxonomy-skill.php, taxonomy.php, archive.php, index.phptaxonomy-skill.html, taxonomy.html, archive.html, index.html
Template lookup order for a “portfolio” CPT and “skill” taxonomy.

In a block theme you can also skip the file: open the Site Editor, go to Templates, add a new template, and pick the single-item or archive template for Portfolio. WordPress saves it as a wp_template post. The block theme lookup order comes from the Theme Handbook.

Custom Post Type Plugins: CPT UI vs ACF vs Pods

If you would rather not write code, three maintained plugins register CPTs through a UI. Numbers below are from the WordPress.org plugin API on November 8, 2026.

PluginVersion / last updateTested up toActive installsBest for
Custom Post Type UI1.19.3 / July 14, 20267.0.81,000,000+CPTs and taxonomies only. Settings map almost 1:1 to register_post_type() arguments, and Tools > Get Code exports PHP you can paste into a plugin.
Advanced Custom Fields6.8.11 / November 2, 20267.1.42,000,000+Sites already using ACF for fields. Post type and taxonomy registration has been in the free plugin since 6.1 (April 2023), next to field groups.
Pods3.3.9.2 / August 31, 20267.1.4100,000+Content models with relationship fields, or Advanced Content Types that use their own database tables instead of wp_posts.
CPT plugins compared, data from api.wordpress.org.

Secure Custom Fields, the WordPress.org-maintained fork of ACF, also registers post types and taxonomies from its UI if you use it instead of ACF.

If you are comfortable with PHP, the code route is the most portable: 15 lines, in version control, no plugin dependency. CPT UI is a good middle ground because you can build the type in the UI, export the code, and drop the plugin later.

Frequently Asked Questions

Where should I put register_post_type() code?

In a small custom plugin (best) or your theme’s functions.php. Code in functions.php disappears when you switch themes, and the entries vanish from the admin with it. A one-file plugin in /wp-content/plugins/ survives theme changes. Either way, hook the registration on init.

Why do my custom post type URLs return 404?

The rewrite rules were not flushed after you registered the CPT. Go to Settings > Permalinks and click Save Changes (no changes needed), or run wp rewrite flush. Do it again after changing rewrite, has_archive, or adding a taxonomy. In a plugin, call flush_rewrite_rules() in the activation hook, never on every init.

What does show_in_rest do in register_post_type()?

It registers REST API routes for the CPT (/wp-json/wp/v2/{rest_base}) and lets the block editor load it. The core docblock describes it as: “Set this to true for the post type to be available in the block editor.” It defaults to false, so a CPT without it gets the classic editor and no REST route.

How do I make my custom post type use the block editor?

Set 'show_in_rest' => true and include 'editor' in supports (it is there by default if you omit supports). If either is missing, use_block_editor_for_post_type() returns false and you get the classic editor.

Where are custom post types stored in WordPress?

Entries live in wp_posts like regular posts, with the CPT key in the post_type column. Custom fields go in wp_postmeta and taxonomy terms in the term tables. The registration itself is not stored in the database: it runs in PHP on every request, which is why removing the code hides the entries.

What is the maximum length of a custom post type key?

20 characters. The post_type column is VARCHAR(20), and register_post_type() returns a WP_Error (post_type_length_invalid) for anything longer. The label shown in the admin can be as long as you like.

What is the difference between hierarchical and non-hierarchical CPTs?

Hierarchical CPTs work like Pages: one entry can be the parent of another in the same post type, giving URLs like /portfolio/parent-item/child-item/. Non-hierarchical CPTs work like Posts and are flat. Use hierarchical only when the content really nests, and add page-attributes to supports so the Parent dropdown appears.

How do I relate one custom post type to another?

Core has no relationship field. The usual options are storing related post IDs in post meta, using ACF’s free Relationship or Post Object fields, using Pods relationship fields, or sharing a taxonomy between both CPTs when the link is really a grouping.

Will my custom post types break if I switch themes?

Only if they were registered in the old theme’s functions.php. The entries stay in the database but nothing tells WordPress what they are, so they disappear from the admin and the front end. Move the registration into a plugin and they come back.

Can I rename or delete a custom post type later?

Changing label, labels, or menu_icon is safe. Changing the key (the first argument) orphans existing entries, because their post_type column still holds the old key. You need to update that column too, for example with a one-off SQL update (UPDATE wp_posts SET post_type = 'new_key' WHERE post_type = 'old_key') run after a backup. Removing the registration hides the entries but does not delete them.

Wrapping Up

The safe defaults: register the CPT on init in a small plugin, keep the key short and prefixed, set 'show_in_rest' => true, add a custom taxonomy if it needs its own categories, and flush rewrite rules once on activation or from Settings > Permalinks. The canonical reference for every argument is register_post_type() on developer.wordpress.org.

Picture of Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 15 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way. Found this article helpful? Buy Me A Coffee

Leave a Reply

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

WordPress Tips Monthly
Get the latest from SmartWP to your inbox.