Creating Custom Post Types in WordPress
This guide covers how to create Custom Post Types (CPT’s) in WordPress. CPT’s are important to WordPress developers because they enable the creation of more complex sites + web-apps than is possible with a default WordPress install.
Custom Post Types are frequently defined with additional data fields called meta fields that can be defined and made editable to admins via meta boxes.
Example applications:
- Jokes — each post contains a joke, which are listed and displayed differently than regular blog posts
- Job Opportunities — include Salary Range and Location meta
- Car Listings — registered users post for-sale listings and specify Make, Model, and Year meta via dynamic dropdown menus
- Beer Reviews — featuring a range of meta fields that include Brewery, Style, and Tasting Score
Custom Post Types can be created (registered) or modified by calling the register_post_type()
function within the init
action.
Custom Taxonomies and the connection to Custom Post Types
Custom Post Types are closely related to the concept of Custom Taxonomies. Taxonomies are a way to group WordPress objects such as Posts by a certain classification criteria. Developers can define Custom Taxonomies to add to WordPress’ default taxonomies: Categories, Tags, Link Categories, and Post Formats.
Although this guide focuses on CPT’s, its important to note that projects are often implemented using a thoughtful combination of Custom Post Types and Custom Taxonomies.
A classic example of a complementary post type + taxonomy is: Book as a Custom Post Type and Publisher as a Custom Taxonomy.
If your Custom Post Type needs to be related to any Custom Taxonomies, they must be identified via the optional taxonomies
argument of the register_post_type()
function. This argument only informs WordPress of the relation and does not register any taxonomies as a side-effect. Custom Taxonomies must be registered on their own via WordPress’ register_taxonomy()
function.
Registering new Custom Post Types
Registering in a Plugin vs. Theme
Custom Post Types can be registered by plugins or by themes via their functions.php
file. It’s generally recommended to go the plugin route to keep a project de-coupled from any particular theme.
In the many cases where CPT’s do not depend on activation or deactivation hooks, they can be defined by a Must-Use Plugin (mu-plugin). This special type of plugin is useful to safeguard against admins (e.g. client stakeholders with admin access) accidentally de-activating any Custom Post Types that are important to their website/app.
If a plugin or theme that registers a CPT becomes deactivated, WordPress’ default behaviour is to preserve the post data in its database, though it will become inaccessible and could break any themes or plugins that assume the CPT exists. The CPT will be restored once whatever plugin or theme that registered it is re-activated.
Basic Definition
Custom Post Types may be registered by calling WordPress’ register_post_type()
function during the init
action with the following arguments: a required one-word post type key, and an optional array of key => value pairs that specify all optional arguments.
The following example implements a function create_my_new_post_type()
that calls register_post_type()
to register a CPT called candy. The last line hooks the function to the init
action using WordPress’ add_action()
function. It could be included as part of a plugin or in a theme’s functions.php
.
Some of the most common optional args are specified: user-facing labels for singular and plural, if the CPT is to be public (appear in search, nav, etc) or not, and whether it should have an archive (list of posts) or not.
function create_my_new_post_type() {
register_post_type( 'candy',
[
'labels' => [
'name' => __( 'Candies' ),
'singular_name' => __( 'Candy' )
],
'public' => true,
'has_archive' => true,
]
);
}
add_action( 'init', 'create_my_new_post_type' );
Tip: Namespacing
It is a good practice to namespace any CPT keys by prefixing their names with a few characters relevant to you or your project followed by an underscore, such as xx_candy
. This helps avoid naming conflicts with other plugins or themes, and is particularly important if you are planning to distribute your project.
Tip: Use singular form for post type keys
The WordPress codex and Handbooks always use a singular form for post type keys by convention, and WordPress’ default types such as ‘post’ and ‘page’ are singular as well.
Detailed Definition
There are a ton of optional arguments that can be specified when registering a Custom Post Type. The WordPress Developer Documentation is the best source to review all of them: [register_post_type()](https://developer.wordpress.org/reference/functions/register_post_type/)
.
Some of the more notable options include:
labels
— array of key => value pairs that correspond to different labels. There are a ton of possible labels but the most commonly specified are ‘name’ (plural) and ‘singular_name’public
— boolean indicating if the post type is to be public (shown in search, etc) or not (default: false)has_archive
— boolean indicating if an archive (list of posts) view should exist for this post type or not (default: true)supports
— array of WordPress core feature(s) to be supported by the post type. Options include ‘title’, ‘editor’, ‘comments’, ‘revisions’, ‘trackbacks’, ‘author’, ‘excerpt’, ‘page-attributes’, ‘thumbnail’, ‘custom-fields’, and ‘post-formats’. The ‘revisions’ option indicates whether the post type will store revisions, and ‘comments’ indicates whether the comments count will show on the edit screen. The default value is an array containing ‘title’ and ‘editor’.register_meta_box_cb
— string name of a callback function that will handle creating meta boxes for the CPT so admins have an interface to input meta datataxonomies
— an array of string taxonomy identifiers to register with the post typehierarchical
— a boolean value that specifies if the CPT behaves more like pages (which can have parent/child relationships) or like posts (which don’t)
The numerous other options enable you to manage rewrite rules (e.g. specify different URL slugs), configure options related to the REST API, and set capabilities as part of managing user permissions.
Adding Meta Fields to a Custom Post Type
Enabling custom-fields
A straightforward way to enable admins to define meta fields as key->value pairs when editing a post is to include the value ‘custom-fields’ in the ‘supports’ array, as part of the args
passed to register_post_type()
.
Adding Meta Boxes to a Custom Post Type
The above ‘custom-fields’ approach works for basic use-cases, however most projects require advanced inputs like dropdown menus, date pickers, repeating fields, etc. and a certain level of data validation.
The solution is defining meta boxes that specify inputs for each of a CPT’s meta fields and handle the validation and save process. Meta boxes must be implemented in a function whose name is passed to register_post_type()
via its args
as a value of the ‘register_meta_box_cb’ option.
Creating meta boxes can be tricky for the uninitiated… Stay tuned for an upcoming post dedicated solely to them!
In the meantime, I would suggest exploring solutions that simplify the process of creating meta boxes. Two excellent options are the open-source CMB2 (Custom Meta-Box 2) and Advanced Custom Fields (ACF), which offers both free and commercial options. I think the commercial ACF PRO version is well worth the $100 AUD fee to license it for unlimited sites including a lifetime of updates and upgrades.
Displaying a Custom Post Type
Posts belonging to a CPT can be displayed using single and archive templates, and can be queried using the WP_Query object.
Single template: single post view
Single templates present a single post and its content. WordPress looks for the template file single-post_type_name.php for a CPT-specific template and if it doesn’t find it, it defaults to the standard single.php
template.
Archive template: list of posts view
Archive templates present lists of posts. A Custom Post Type will have an Archive if it was registered with the optional has_archive
argument set to a value of true
(default: false
).
To create an archive template for your CPT, create a template file that follows the convention: archive-post_type_name.php. If WordPress doesn’t find this file, it defaults to the standard archive.php
template.
Using the WP_Query object
WP_Query can be used in widget definitions, in templates, etc. to present posts belonging to a CPT. The following example queries for published posts of the type ‘candy’ and then loops over the results, presenting each one’s title and content as items in a list.
<?php
$args = [
'post_type' => 'candy',
'post_status' => 'publish',
]);
$candies = new WP_Query( $args );
if( $candies->have_posts() ) :
?>
<ul>
<?php
while( $candies->have_posts() ) :
$candies->the_post();
?>
<li><?php printf( '%1$s - %2$s', get_the_title(), get_the_content() ); ?></li>
<?php
endwhile;
wp_reset_postdata();
?>
</ul>
<?php
else :
esc_html_e( 'No candies... Go get some candy!', 'text-domain' );
endif;
?>
The wp_reset_postdata()
call is important to reset WordPress back to the original loop, so other functions that depend on it will work properly. Reference: https://developer.wordpress.org/reference/functions/wp_reset_postdata/