WordPress Custom Post Type
Post types are a way to categorize different types of content in WordPress.
WordPress has already the following native post type:
- Post
- Pages
- Attachments
- Revisions
- Navigation menu
- custom CSS
- Changeset
Most probably you just knew about the first three in the list.
And you can extend these wordpress post type with your own.
To do this you here it is a little function recap.
Hook
custom post type definition
Hook
add_action( 'init', 'custom_posttype_def', 0 );
custom post type definition
function custom_posttype_def()
{
// Set UI labels for Custom Post Type
$labels = array(
'name' => _x( 'Movies', 'Post Type General Name', 'twentytwenty' ),
'singular_name' => _x( 'Movie', 'Post Type Singular Name', 'twentytwenty' ),
'menu_name' => __( 'Movies', 'twentytwenty' ),
'parent_item_colon' => __( 'Parent Movie', 'twentytwenty' ),
'all_items' => __( 'All Movies', 'twentytwenty' ),
'view_item' => __( 'View Movie', 'twentytwenty' ),
'add_new_item' => __( 'Add New Movie', 'twentytwenty' ),
'add_new' => __( 'Add New', 'twentytwenty' ),
'edit_item' => __( 'Edit Movie', 'twentytwenty' ),
'update_item' => __( 'Update Movie', 'twentytwenty' ),
'search_items' => __( 'Search Movie', 'twentytwenty' ),
'not_found' => __( 'Not Found', 'twentytwenty' ),
'not_found_in_trash' => __( 'Not found in Trash', 'twentytwenty' ),
);
// Set other options for Custom Post Type
$args = array(
'label' => __( 'movies', 'twentytwenty' ),
'description' => __( 'Movie news and reviews', 'twentytwenty' ),
'labels' => $labels,
// Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
// You can associate this CPT with a taxonomy or custom taxonomy.
'taxonomies' => array( 'genres' ),
/* A hierarchical CPT is like Pages and can have
* Parent and child items. A non-hierarchical CPT
* is like Posts.
*/
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
'show_in_rest' => true
);
// Registering your Custom Post Type
register_post_type( 'movies', $args );
}
There is another way to create a custom post type. It’s using the plugin Custom Post Type UI (or CPTUI). In this case you can create your post types directly in the wordpress admin with a simple UI.
Of course it depends on what you need from Custom Post Types.
If you are creating a plugin it’s better to create them inside it.
If you need them only for you personal use then it’s easer to use CPTUI.
That’s it