WP: Custom Post Type

By default we can create a post or a page in WordPress. These are basically WordPress post types. The good thing is we don’t necessarily restrict ourselves to just two of these. WordPress allows us to create our own custom post types.

Let’s say, we’d like to create a post type called “Events” and then create new posts under the custom post type called “Events”.

How do we do that? It’s quite simple. Let’s have a look at the code below which will help us achieve this goal.

<?php 

function ob_post_types() {
	register_post_type('event', array(
		'public' => true,
		'labels' => array(
			'name' => 'Events'
		),
		'menu_icon' => 'dashicons-calendar'
	));
}

add_action('init', 'ob_post_types');

?>

We have created our own function called ob_post_types which will be triggered automatically on the WordPress action hook called init.

Inside our function, we have a register_post_type, that registers the custom post type event and accepts an array of settings for this custom post type.

For example, is it publicly accessible? Yes. What labels does it have? One of the labels we’d like it to have is name (which is set to ‘Events’ in our example above). We’d also like to give it an icon by using something called dashicons in WordPress. We’ll see more about that in future posts.

For now, the code above, when added to functions.php of our newly developed theme, would render a custom post type called ‘Events’ in the site’s WP-Admin dashboard.