Creating a Custom Post Type in WordPress
Custom Code Solution
This code creates a new custom post type. Place this code in your theme's functions.php
file or in a site-specific plugin:
Basic custom post type registration code:
function register_movie_post_type() {
$labels = array(
'name' => 'Movies',
'singular_name' => 'Movie',
'menu_name' => 'Movies',
'add_new' => 'Add New Movie',
'add_new_item' => 'Add New Movie',
'edit_item' => 'Edit Movie',
'new_item' => 'New Movie',
'view_item' => 'View Movie',
'search_items' => 'Search Movies',
'not_found' => 'No movies found',
'not_found_in_trash' => 'No movies found in Trash'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_rest' => true, // Enables Gutenberg editor
'menu_icon' => 'dashicons-video-alt2',
'supports' => array('title', 'editor', 'thumbnail', 'excerpt'),
'rewrite' => array('slug' => 'movies')
);
register_post_type('movie', $args);
}
add_action('init', 'register_movie_post_type');
Hook the function to flush rewrite rules (run once after adding the custom post type):
function flush_rewrite_rules_once() {
if (get_option('needs_rewrite_flush') == true) {
flush_rewrite_rules();
update_option('needs_rewrite_flush', false);
}
}
add_action('init', 'flush_rewrite_rules_once', 20);
function set_needs_rewrite_flush() {
update_option('needs_rewrite_flush', true);
}
register_activation_hook(__FILE__, 'set_needs_rewrite_flush');
Customization Options
To modify the custom post type:
- Change 'movie' to your desired post type name
- Update the
$labels
array text
- Modify the
supports
array to include desired features
- Adjust the
menu_icon
(use WordPress dashicons)
- Change the rewrite slug as needed
Plugin Alternative
If you prefer using a plugin, here are reliable options:
-
Custom Post Type UI - User-friendly interface for creating custom post types
-
Pods - Advanced custom post type management with additional features
Important Notes
- After adding a new custom post type, visit Settings > Permalinks and save to flush rewrite rules
- Choose a unique post type name that doesn't conflict with existing WordPress post types
- The post type name should be lowercase and no more than 20 characters
- Always backup your site before making changes to
functions.php