Custom Post Type in WordPress

What is Custom Post type in WordPress?

WordPress can store and show many different types of content that is called as the posts in term of WordPress. A single collection of data or content is called as post, though post is also a specific built in post type that is used widely by the WordPress users. If we talk in term of database, all the post types are stored in the same table, that is the wp_posts database table, but that are differentiated by a column or attribute of the table that is post_type.
WordPress provides few built in post_type. that means when we install few post type are created by default as the WordPress backbone, which are…

  • Post : This stores the articles or our blog post, and in post_type attribute the value stored is ‘post’.
  • Page : This stores the Page of the website, and in post_type attribute the value stored is ‘page’. Unlike the post, page can have different page templates that are made while we are developing the theme. Pages can be organized in a hierarchical manner, that means pages can be parents to other pages, but by default pages cannot be have categories and tags.
  • Attachment : This stores the media or the attachment like images, documents etc. of the website, and in post_type attribute the value stored is ‘attachment’.
  • Revision : This stores the history or old data of a post or page , and in post_type attribute the value stored is ‘revision’.
  • Navigation menu : This stores the menus of the website, and in post_type attribute the value stored is ‘nav_menu_item’.

Custom Post Types

Custom post types are the post types which are created by us in order to distinguish the nature of the data we want to represent on our website. A custom post type can be create in WordPress using the register_post_type() function. This function allows us to declare a new post type with its labels, availability, supported features, and other specifics.

We must have to call register_post_type() before the admin_menu get called and after after_setup_theme action hooks start working. A best hook to perform this operation is the init hook.

When we need Custom Post type in WordPress?

We can add any kind of data in WordPress posts and later we will be able to sort them using taxonomy (i.e. categories and tags), But ideally not fit in all cases. here are few conditions where we have to create a custom post type, custom taxonomy, or may be both of them:

  1. It doesn’t should be a piece of a sequential arrangement of sections. For example our WordPress glossary.
  2. Some data we are putting on website is not like a post. For example our offers, Testimonials, Places, Recipes etc.
    Categories and Tags are not sufficient to group and bifurcate that particular content. For instance: specific sections in our recipes.
  3. You need additional fields called as custom meta box to enter more information with your content. i.e. Preparation time, Ingredients, Nutrition facts for recipes.
  4. We need to display that data in certain manner or format than posts or pages.

Lets investigate with a genuine example, Suppose we are having a blog where we regularly publish recipes among other posts. However our recipes are generally welcomed by your group of users. but still you wanted to add extra features to your recipes such as Preparation time, sort by course, type, preparation time , ingredients etc.

So this is the perfect time when we have to create a custom post type in order to achieve our requirement, and we have to add custom taxonomy for sorting between course and ingredients. This functionality will give another ease of accessing and sorting their require recipes instead of digging all the posts.

Another prominent example would be making a portfolio.In case we’re a a web developer sharing our work in our blog post, then it will be complex to search particular data. Creating a separate portfolio post type will permit our clients to effectively search through the majority of our work.

How to use Custom Post type in WordPress?

Creating Custom Post type in WordPress doesn’t really tough task it’s just a copy paste and change the text. But this need to be done wisely else you never know… fatal error occur.. site down….

So the custom post type can be made using plugin or the manually. we are going to explain both method to create the CPT.

Method 1 : Creating Custom Post type in WordPress Using Plugin.

The most straightforward way to make a custom post type in WordPress is by using a plugin. This strategy is prescribed for beginners since it is protected and super simple.

First thing we need to do is install and activate the Custom Post Type UI plugin version 1.2.4 . We are already familiar with how to install the Plugin, Once we are done with installation we need to activate, the plugin will create a new menu in our WordPress admin menu as CPT UI.

Now we need to go to CPT UI » Add New in order to create a new CPT.

The Custom Post Type UI plugin also allows us to create custom taxonomies.

CPT UI has two different menu to add the custom taxonomy and custom post type. On our right side, we have the form which we need to fill in order to create our custom post type. On our left, in menu we have Add/Edit Taxonomy, we need to click on it if we want to create a custom taxonomy.

As we click on the Add/Edit post type, we see a form that is divided in two columns, first column is consist of Slug, label and description and second column is having Labels and Settings, etc. In order to create a post type we need to fill slug lables and description first. Keep in mind that slug must not have any white space and keep a standard format of writing slug is recipes, portfolio, real_estate, hotel_business.

In the next we need to fill the Labels, you need to provide a label for your custom post type. This label will appear in your WordPress admin bar just like posts and pages. It also needs to be plural to make sense. e.g. Movies, Recipes, Deals, Glossary, etc.

After that you need to provide a singular form for your label. This singular form will be used by WordPress to show instructions and other user interface elements.

Lastly enter a description for your custom post type. This description is simply used to describe what your post type does.

Now you can click on the ‘Create Custom Post Type’ button to add your new custom post type. That’s all.

You can also click on the Advanced Label Options and Advanced Options links to customize more options for your custom post type.

Method 2 : Manually creating Custom Post type in WordPress.

function theme_create_post_type() {
         $labels = array(
 	'name' => 'Products',
    	'singular_name' => 'Product',
    	'add_new' => 'Add New Product',
    	'add_new_item' => 'Add New Product',
    	'edit_item' => 'Edit Product',
    	'new_item' => 'New Product',
    	'all_items' => 'All Products',
    	'view_item' => 'View Product',
    	'search_items' => 'Search Products',
    	'not_found' =>  'No Products Found',
    	'not_found_in_trash' => 'No Products found in Trash', 
    	'parent_item_colon' => '',
    	'menu_name' => 'Products',
    //register post type
	register_post_type( 'product', array(
		'labels' => $labels,
		'has_archive' => true,
 		'public' => true,
		'supports' => array( 'title', 'editor', 'excerpt', 'custom-fields', 'thumbnail','page-attributes' ),
		'taxonomies' => array( 'post_tag', 'category' ),	
		'exclude_from_search' => false,
		'capability_type' => 'post',
		'rewrite' => array( 'slug' => 'products' ),
add_action( 'init', 'theme_create_post_type' );

Custom Interaction Messages

WordPress generates a number of messages triggered by user actions. Updating, publishing, searching, etc., in the back end all lead to messages which — by default — are tailored to regular posts. You can change the text of these messages easily by using the post_updated_messages hook.

function my_updated_messages( $messages ) {
  global $post, $post_ID;
  $messages['product'] = array(
    0 => '', 
    1 => sprintf( __('Product updated. <a href="%s">View product</a>'), esc_url( get_permalink($post_ID) ) ),
    2 => __('Custom field updated.'),
    3 => __('Custom field deleted.'),
    4 => __('Product updated.'),
    5 => isset($_GET['revision']) ? sprintf( __('Product restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
    6 => sprintf( __('Product published. <a href="%s">View product</a>'), esc_url( get_permalink($post_ID) ) ),
    7 => __('Product saved.'),
    8 => sprintf( __('Product submitted. <a target="_blank" href="%s">Preview product</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
    9 => sprintf( __('Product scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview product</a>'), date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
    10 => sprintf( __('Product draft updated. <a target="_blank" href="%s">Preview product</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
  return $messages;
add_filter( 'post_updated_messages', 'my_updated_messages' );

Using Custom Templates for CPT Archives and Single Entries

If you like to customize the appearance of the archive page of your custom post type, then you can use your own template for the custom post type archive template. To achieve this all you need to do is, create new template file in your theme directory and name it archive-customposttype.php. Replace customposttype with the name of your custom post type.

To Begin, you can copy existing contents of your theme’s archive.php to archive-customposttype.php template and then start changing it to shape to your requirements. Now when the archive page of this custom post type is accessed, this template will be automatically display it.
Using the same method, you can create custom template for your post type’s single page. To achieve this you just need to create single-customposttype.php in your theme directory. Don’t forget to replace customposttype with the name of your custom post type.

You can get started by copying the contents of your current theme’s single.php template into single-customposttype.php template and then start changing it to meet your requeirements.

Displaying Custom Post Types on The Front Page

One huge advantage of using custom post types is that it keeps your custom content types separate from your regular posts or page. However, if you like them to display in your regular post, then you can do so by adding this code into your theme’s functions.php file or a site-specific plugin:

add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

function add_my_post_types_to_query( $query ) {
	if ( is_home() && $query->is_main_query() )
		$query->set( 'post_type', array( 'post', 'movies' ) );
	return $query;

About Pashupatinath Mishra

Pashupatinath Mishra is Software Developer and our Fulltime blogger. He is having good knowledge on the Different Technologies and also having shareable knowledge on Nutrition, Science Topics, Travel and History.


Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.