How to Create Custom Post type in WordPress
What is Post Type in WordPress
WordPress can display many types of content. In wordpress we create “Posts, Pages”, it is also a post type called “post, page” respectively. There are some default post types in wordpress, these are
- Post (Post Type: ‘post’)
- Page (Post Type: ‘page’)
- Attachment (Post Type: ‘attachment’)
- Revision (Post Type: ‘revision’)
- Navigation menu (Post Type: ‘nav_menu_item’)
What is Custom Post Type
These are the new post type that you can create using register_post_type() function in wordpress. Call this function using wordpress hook, good hook to call this function is init hook.
Below is an example to create “Product” post type using register_post_type() function.
[php]
function register_product_posttype() {
$labels = array(
‘name’ => _x( ‘Products’, ‘Post Type General Name’, ‘text_domain’ ),
‘singular_name’ => _x( ‘Product’, ‘Post Type Singular Name’, ‘text_domain’ ),
‘menu_name’ => __( ‘Product’, ‘text_domain’ ),
‘parent_item_colon’ => __( ‘Parent Product:’, ‘text_domain’ ),
‘all_items’ => __( ‘All Products’, ‘text_domain’ ),
‘view_item’ => __( ‘View Product’, ‘text_domain’ ),
‘add_new_item’ => __( ‘Add New Product’, ‘text_domain’ ),
‘add_new’ => __( ‘New Product’, ‘text_domain’ ),
‘edit_item’ => __( ‘Edit Product’, ‘text_domain’ ),
‘update_item’ => __( ‘Update Product’, ‘text_domain’ ),
‘search_items’ => __( ‘Search Products’, ‘text_domain’ ),
‘not_found’ => __( ‘No Products found’, ‘text_domain’ ),
‘not_found_in_trash’ => __( ‘No Products found in Trash’, ‘text_domain’ ),
);
$args = array(
‘label’ => __( ‘product’, ‘text_domain’ ),
‘description’ => __( ‘Product information pages’, ‘text_domain’ ),
‘labels’ => $labels,
‘supports’ => array( ‘title’, ‘editor’, ‘excerpt’, ‘author’, ‘thumbnail’, ‘comments’),
‘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’,
);
register_post_type( ‘product’, $args );
}
// Hook into the ‘init’ action
add_action( ‘init’, ‘register_product_posttype’, 0 );
[/php]
After integrating this code in your themes functions.php, you will see a menu entry of your custom post type in your wordpress admin.
You should be able to add posts, view the post list in the admin and also visit the published posts on the website.
Note: After adding CPT in your wordpress admin you need to update your permalinks.