By default WordPress has two post types: posts and pages. In fact a page is also a post with a post_type of page. We can create other post types as per the need of the website. A custom post type is stored in the database with a different post_type value to separate its content from the default post types.

A rule of thumb when deciding to create post types is whether the content needs a page other than the standard blog listing or a static page. If it does not, then simply creating a category will suffice.

In this lesson, we will create two new post types, teacher and course. If we create posts about teachers or courses as generic posts, they will show up in the blogs section. By creating a separate post type we can ensure that teacher posts, course posts, and blog posts are treated separately.

Must use plugins

It is a best practice not to write the code for registering custom post types in the functions.php file because if the theme is disabled, then the custom post type will not be accessible. The code for registering a custom post type can be stored as a plugin but it has the same demerit. If the plugin is deactivated, the custom post type will be lost. If the theme or plugin containing the custom post type code is disabled or deactivated, the content remains in the database but there is no way to view it.

The best practice is to place the code in a must-use plugin file which will be used in any case. Must-use plugins are placed in a separate folder. First, navigate to the website’s folder.

Right-click the website’s name in Local and choose the “Go to site folder” or “Reveal in finder” option.

Once inside the website’s folder, open the app folder, then navigate to public folder, and finally open the wp-content folder. This folder has further subfolders, one of which is the theme folder, where we have created a number of files so far. Then there is a plugins folder which contains normal plugins used by the website. We will create a new folder inside wp-content with the name mu-plugins for the must-use plugins. All PHP files in this folder are automatically loaded and activated by WordPress.

Open the mu-plugins folder with VS Code and create a new PHP file named school-custom-post-types.php. Since this is a PHP file, we need to begin with the opening PHP tag <?php and then write code for registering the new custom post type.

Get hands-on with 1200+ tech skills courses.