Hello World Master

Tutorials, articles and quizzes on Software Development

PHP > Articles

Creating a custom post type in WordPress with PHP

WordPress allows us to have posts of different types we can organize and group. We could always download a plugin to create custom post types, but why not create our own plugin from scratch to see how it works?

Prerequisites

You should know how to create and structure a basic WordPress plugin. If you don’t check out this link and go through this tutorial series!

Of course, basic knowledge of PHP will definitely help here, so if you want a refresher check out this series as well.

Calling the function that creates a new custom post type

The function that creates our custom post type is called

register_post_type

but we need to call it before the init action, so lets create a PHP function that will call register_post_type inside of it. Lets call it customPostInit

function customPostInit() {


}

add_action( 'init', 'customPostInit' );

Inside the customPostInit function, we want to call register_post_type. Lets create a post type of reviews

function customPostInit() {
   register_post_type( 'reviews' );
}

add_action( 'init', 'customPostInit' );

When we activate our plugin we don’t see anything different happen. We need to use the second parameter of register_post_type.

The reason why I didn’t use the arguments in the first place is because there are a lot of arguments that get passed down to the args array.

Every other tutorial I’ve see about custom post types deals with a LONG arguments array which is just too overwhelming for those who are just learning how to build a WordPress plugin.

So lets focus on the ones that we need, right now because there’s just too many parameters. I will be writing separate articles.

‘public’ key value pair in argument array

The public argument allows us to see the post in WordPress admin

function customPostInit() {
  $args = array(
    'public' => true
  );
  register_post_type( 'reviews', $args );
}

Using label key to set the name of our custom post type in the menu

Now we see two menu items that say posts, but we want it to say reviews, lets add the key value for label into our args array and set it to ‘Reviews’

function customPostInit() {
  $args = array(
    'public' => true,
    'label' => 'Reviews'
  );
  register_post_type( 'reviews', $args );
}

Adding fields to our custom posts (taxonomies)

We’re able to add a title and content to our new custom post, but we don’t have any taxonomies that we can add to our custom post.

Taxonomies are extra characteristics relating to our post. The two main examples of this are categories and tags.