Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 68 ยท Custom Post Types, Taxonomies and Fields

Custom Post Types

Learn to create WordPress custom post types with register_post_type(): arguments, labels, supports, show_in_rest, archives, rewrite, capabilities and templates.

WordPress ships with a few kinds of content: posts, pages, attachments and a handful of internal types. A post type is a label stored in the post_type column of the wp_posts table (see the database schema). A blog entry has the value post, a page has page. When your site needs something else, such as books, events, recipes or portfolio projects, you can register your own custom post type (CPT). It then gets its own admin menu, its own list screen, its own editor and its own URLs.

Using a CPT keeps different kinds of content apart. Editors see "Books" in the menu instead of a mixed list of posts with special categories, and your templates and queries can target exactly that content. This lesson explains register_post_type(), the arguments that matter, how templates are chosen, and the mistakes that cause empty archives and 404 errors.

WordPress cannot run on this site, so the real code below is read-only. The runnable examples are plain-PHP stand-ins that validate arguments and generate names the way WordPress does. They are simplified copies of the behavior, not core code.

Registering a post type

You register a CPT by calling register_post_type() inside a callback for the init action. Registering earlier or later breaks things, because rewrite rules and menus read the registry during init and afterwards. Hooks are covered in actions and filters.

PHP
<?php
function acme_register_book_post_type(): void {
    $labels = [
        'name'               => 'Books',
        'singular_name'      => 'Book',
        'add_new_item'       => 'Add New Book',
        'edit_item'          => 'Edit Book',
        'all_items'          => 'All Books',
        'search_items'       => 'Search Books',
        'not_found'          => 'No books found.',
    ];

    register_post_type( 'book', [
        'labels'       => $labels,
        'public'       => true,
        'has_archive'  => true,
        'show_in_rest' => true,
        'menu_icon'    => 'dashicons-book',
        'supports'     => [ 'title', 'editor', 'thumbnail', 'excerpt', 'revisions' ],
        'rewrite'      => [ 'slug' => 'books' ],
    ] );
}
add_action( 'init', 'acme_register_book_post_type' );

The first argument is the post type key. It is what gets stored in the database, so choose it carefully:

  • It can use only lowercase letters, numbers, dashes and underscores.
  • It can be at most 20 characters long.
  • It must not clash with a reserved name such as post, page, attachment, revision, nav_menu_item or the internal wp_* types.
  • Prefix it if it is generic. A plugin that registers event may clash with another plugin that also registers event. Something like acme_event is safer.

The key is permanent. If you rename it later, all existing rows keep the old value and disappear from your admin screen until you update them.

Register post types from a plugin, not from a theme's functions.php. If the theme is switched, the CPT disappears from the admin menu and the content looks lost, even though the rows are still in the database. See your first plugin.

flowchart LR
    A["init action fires"] --> B["register_post_type('book', args)"]
    B --> C["Registry of post types"]
    C --> D["Admin menu and list screen"]
    C --> E["Rewrite rules and archive URL"]
    C --> F["REST route /wp/v2/book"]
    C --> G["Template hierarchy: single-book.php"]

One call during init feeds the admin, the URL system, the REST API and template selection.

The arguments that matter

register_post_type() accepts many arguments. These are the ones you will use all the time:

Argument Default What it does
public false Master switch. When true, the type is visible on the front end and in the admin, and it sets sensible defaults for show_ui, publicly_queryable and show_in_nav_menus.
show_in_rest false Exposes the type in the REST API. It is also required for the block editor: without it the classic editor is used.
has_archive false Creates an archive page listing all items (true uses the rewrite slug; a string sets a custom slug).
supports title, editor Which editor features appear: title, editor, author, thumbnail, excerpt, comments, revisions, custom-fields, page-attributes, post-formats.
rewrite true The URL slug and options such as with_front. Use false to turn pretty URLs off.
capability_type post The base name used to build permission names (see below).
hierarchical false true allows parent and child items, like pages. Pair it with page-attributes in supports.
menu_icon generic pin A Dashicons class such as dashicons-book, a URL or a base64 SVG data URI.
menu_position below Comments A number that moves the menu; larger means lower.
taxonomies none Existing taxonomies to attach, such as category (see custom taxonomies).
template none A list of blocks that new items start with in the block editor.

Some combinations are worth knowing:

  • public => false with show_ui => true makes a type that editors manage in the admin but visitors can never open. This is a good fit for internal data such as testimonials that you only print through a block or shortcode.
  • exclude_from_search and publicly_queryable give finer control than public, for example a type that has single pages but stays out of search results.
  • labels is optional. If you leave it out, WordPress generates generic labels from the label argument or the key. Provide at least name and singular_name, and ideally the full set, so the admin reads naturally.

Archives, single pages and templates

A CPT does not need new code to display. After registration, WordPress picks templates for it with the usual template hierarchy:

  • A single item looks for single-book.php, then single.php, then singular.php, and finally index.php.
  • The archive (only when has_archive is on) looks for archive-book.php, then archive.php, then index.php.

In a block theme the same names are HTML files, for example templates/single-book.html.

To query your type in a custom loop, pass its key to WP_Query:

PHP
<?php
$books = new WP_Query( [
    'post_type'      => 'book',
    'posts_per_page' => 6,
    'orderby'        => 'title',
    'order'          => 'ASC',
] );

If you want books to appear on the blog index too, you can add the type to the main query with pre_get_posts. See the main query lesson.

Registering a type with a rewrite slug adds new rewrite rules. WordPress stores compiled rules in the database, so a freshly registered CPT can show a 404 until the rules are rebuilt. The simplest fix while developing is to visit Settings, Permalinks and press Save. In a plugin, flush the rules once on activation, never on every request. Permalinks and rewrite rules explains why, and activation and uninstall shows the hook.

Capabilities: who may edit books?

By default a CPT uses capability_type => 'post', so anyone who can edit posts can edit your items. If you pass 'book', WordPress builds permission names from it: edit_books, edit_others_books, publish_books, read_private_books and so on. You can give an array such as ['book', 'books'] when the plural is irregular.

An important catch: no role has those new capabilities until you grant them. If you set capability_type => 'book' and map_meta_cap => true but forget to add the capabilities to a role, even administrators will not see the menu. Many plugins therefore stay with 'post' unless they truly need separate permissions. Users, roles and capabilities covers granting them.

Validate arguments with a stand-in registry

The stand-in below follows the key rules and the main defaults: key format and length, reserved names, duplicates, supports validation, and the way public implies other flags. It returns an error list instead of a WP_Error, because plain PHP has no such class.

PHP A post type registry that validates arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the first result: show_ui follows public, and show_in_rest decides which editor is used. The later calls fail with messages that mirror the real rules: reserved key, wrong length or characters, a bad supports value, and a duplicate key.

Capability names and template candidates

This second stand-in generates the capability names for a capability_type and lists the template files WordPress would try. It only builds names and file lists, so you can see the pattern.

PHP Capability names and template candidates for a CPT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The theme in this example has no single-book.php, so a single book falls back to single.php. The archive finds archive-book.php first. Creating the more specific file is how you give one post type its own layout.

Common mistakes

  • Registering outside init. Hook the call to init.
  • Forgetting show_in_rest. The block editor stays off and the REST API shows nothing.
  • Forgetting has_archive. /books/ returns a 404 or shows the blog index instead of a list.
  • Not refreshing permalinks. New slugs 404 until the rules are flushed once.
  • Keys over 20 characters. WordPress refuses to register the type.
  • Using a custom capability_type without granting it. The menu vanishes for everyone.
  • Registering in a theme. Content seems to vanish when the theme changes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On which hook should register_post_type() be called?

    init runs at the right moment for registering post types, taxonomies and rewrite rules, before the request is parsed.
  2. 2. What happens if you register a post type without show_in_rest set to true?

    show_in_rest defaults to false. The block editor needs the REST API, so the type falls back to the classic editor.
  3. 3. What is the maximum length of a post type key?

    The post_type column is limited, and WordPress refuses keys longer than 20 characters.
  4. 4. A visitor opens /books/ and sees a 404, but single books work. Which argument is most likely missing?

    Without has_archive there is no archive URL for the post type, so the list page does not exist.
  5. 5. Why is it better to register a CPT in a plugin than in a theme?

    Content should outlive a design. A plugin keeps the post type registered whatever theme is active.

Summary

  • A post type is a value in wp_posts.post_type; register_post_type() gives a new value its own admin screens, URLs and REST routes.
  • Call it on init, from a plugin, with a lowercase key of at most 20 characters that is not reserved.
  • public, show_in_rest, has_archive, supports, rewrite and capability_type are the arguments you will use most; show_in_rest is required for the block editor.
  • Templates follow the hierarchy: single-{type}.php and archive-{type}.php come before the generic files.
  • Flush rewrite rules once on activation (or save the Permalinks screen while developing).
  • A custom capability_type needs capabilities granted to roles.
  • The runnable examples are plain-PHP stand-ins that follow the real rules in a simplified way.

Next: Custom Taxonomies