How to create WordPress custom post type

-

This tutorial explains in detail step by step on creating custom post type of a WordPress on developing a theme or plugin.

If you are developing either a plugin or theme for different post type like eg. job, book or anything, then, you have to follow this tutorial.

These are the steps and codes on creating custom post type for both theme and plugin:

Step 1: Register custom post type function, let say custom post type is ‘book’

function my_prefix_register_book() {
            register_post_type( 'my_book',
		[
			'labels'      => [
				'name'          => __(  'book', 'text-domain'  ),
				'singular_name' => __(  'Book', 'text-domain'  ),
				'add_new_item'  =>  __(  'Add Book', 'text-domain'  ),
                'edit_item'     => __( 'Edit Job' ),
				'all_items'		=>	__(  'All Books', 'text-domain'  )
			],
            'query_var'     =>  true,
            'hierarchical'  =>  false,
            'show_ui'     =>  true,
            'capability_type'  => 'post',
            'exclude_from_search' => false,
			'public'      => true,
			'has_archive' => 'books',
			'rewrite'     => [ 'slug' => 'book' ], // my custom slug
            'supports'	=>	[ 'title', 'editor' ]
			]
	        );

        }

Let’s summarize the above function and variables on above function:

  1. register_post_type function

This is the main function for registering custom post type.

2. ‘my_book’

Is the unique ID of a custom post type

3. labels

These are label text displayed on WordPress dashboard of a custom post

Step 2: Hook the above function on init action if you are registering this custom post type through a plugin.

add_action( 'init', 'my_prefix_register_book', 10 );

Once you hook the custom post type function into init hook, it will be visible on WordPress dashboard.

Leave a Comment