WordPress Custom Post Types

WordPress has posts and pages, but many sites need another type of content: books, products, events, portfolios or movies. A custom post type (CPT) is your own type of content, with its own menu in the dashboard. It uses the same wp_posts table, but has a different post_type value.

Register a post type

Use register_post_type() on the init hook. Put the code in a plugin (not in the theme), so the content stays when the theme changes.

<?php
/**
 * Plugin Name: Books
 */
function tc_register_book_type() {
	register_post_type( 'book', array(
		'labels'       => array(
			'name'          => 'Books',
			'singular_name' => 'Book',
			'add_new_item'  => 'Add New Book',
		),
		'public'       => true,
		'has_archive'  => true,
		'rewrite'      => array( 'slug' => 'books' ),
		'menu_icon'    => 'dashicons-book',
		'show_in_rest' => true,
		'supports'     => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
	) );
}
add_action( 'init', 'tc_register_book_type' );

// Flush the permalinks once, when the plugin is activated
register_activation_hook( __FILE__, function () {
	tc_register_book_type();
	flush_rewrite_rules();
} );
Terminal output

$ wp plugin activate tc-books
Plugin 'tc-books' activated.
Success: Activated 1 of 1 plugins.
$ wp post-type list –public=1 –fields=name,label,has_archive
name label has_archive
post Posts
page Pages
attachment Media
book Books 1
$ wp post create –post_type=book –post_title="The Alchemist" –post_content="A story about following your dream." –post_status=publish –porcelain
5
$ wp post list –post_type=book –fields=ID,post_title,post_type,post_status
ID post_title post_type post_status
5 The Alchemist book publish

Important arguments

ArgumentMeaning
labelsAll the texts in the dashboard (name, add new, search and more)
publicShow it on the front and in the dashboard
has_archiveMake an archive page like /books/
rewriteThe URL base. 'slug' => 'books'
supportsEditor features: title, editor, thumbnail, excerpt, custom-fields, comments, author
show_in_restNeeded for the block editor and the REST API
hierarchicaltrue makes it like pages (parent and child)
menu_icon, menu_positionIcon and place in the admin menu
capability_typePermissions, like post

See it on the site

Terminal output

$ curl -s -o /dev/null -w "%{http_code}\n" http://example.com/books/
200
$ curl -s -o /dev/null -w "%{http_code}\n" http://example.com/books/the-alchemist/
200
$ curl -s "http://example.com/wp-json/wp/v2/book?_fields=id,slug,title" | jq -c '.[]'
{"id":5,"slug":"the-alchemist","title":{"rendered":"The Alchemist"}}
$ wp eval 'echo get_permalink(5);'
http://example.com/books/the-alchemist/

The book has its own archive, its own single URL and a REST API route. WordPress chooses the template single-book.php and archive-book.php for it (see Template Hierarchy).

Show the books in a template

<?php
$books = new WP_Query( array( 'post_type' => 'book', 'posts_per_page' => 10 ) );
while ( $books->have_posts() ) {
	$books->the_post();
	echo '<h3>' . esc_html( get_the_title() ) . '</h3>';
}
wp_reset_postdata();

Common mistakes

  • The 404 error on the new URLs: flush the rewrite rules once. Open Settings > Permalinks and click Save, or run wp rewrite flush. Never call flush_rewrite_rules() on every page load.
  • Post type name too long: the name can have 20 characters at the most, in small letters, without spaces.
  • Content is lost when you change theme: that happens when the CPT is registered in the theme. Use a plugin.
  • A name which is already used: avoid names like post, page, action, order and theme.
Note: Add a prefix to the name if you build a plugin to sell, for example tc_book, so it does not clash with other plugins. Next: Custom Taxonomies.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Register a Movie custom post type
Add a hierarchical Level taxonomy to a Course post type
Interview Questions & Answers
What is the difference between a custom post type and a custom taxonomy?