Create your own custom post types in WordPress

Custom posts types in WordPress are the content types like posts, pages and attachments. In a custom post type, all the content are of the same type. The posts, pages, attachments are default post types in WordPress that already exists after installing WordPress on the server.

But do you know, that you can also create your own post type? There are lots of plugins exists that have their own post type. For example, if you are using WooCommerce plugin, then all the products added by this plugin are custom post type which is name as “Products”. Similarly, The Easy Digital Downloads plugin has the custom post type “Downloads”.

WordPress gives a great opportunity for developers by letting them create their own custom post types. With this feature of WordPress, many talented WordPress developers are showing their creativity in the WordPress world by creating great plugins and solutions. Custom post types can be also implemented in theme.

Now in this article, I am going to show you how to create your own custom post types manually by writing your own PHP code.

Code to create your custom post type in WordPress

Let’s see the code below which is a simple code that will create the custom post type “books”.

// Define the custom post type function
function books_post_type() {
    register_post_type( 'books',
            'labels' => array(
                'name' => __( 'Books' ),
                'singular_name' => __( 'Book' )
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'books'),
// Hook our custom post type function
add_action( 'init', 'books_post_type' );

You can put the above code in your plugin’s file or in theme’s functions.php file. You will see the custom post type books have been created and you can see the admin menu “Books” added.

Our code is the simplest code just to show you how to create a custom post type. There are lots of parameters you can pass to make it for your use for your client.

From the code above, you can see that we have used register_post_type() inside our function and pass the arguments inside it. Later we pass it to our init action hook. The init hook fires after WordPress has finished the loading task, but before any headers are sent.

The register_post_type taking two arguments as you can see below:

<?php register_post_type( $post_type, $args ); ?>

$post type: This is the post type. It should be unique to prevent from other post types. The argument is a string type. It can be a maximum of 20 characters. Also, it can not contains capital letters, underscores and spaces.

To understand about the register_post_type function in details, visit the guide of register_post_type from official WordPress site.

Leave a Reply

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