Creating Custom Post Types In WordPress Manually

WordPress

WordPress is a extremely powerful platform offering more than just the blogging capabilities it was originally created for. Since it’s creation, WordPress has grown into a vast CMS platform that allows users with nearly any goal in mind a great place to build. New features such as custom menus, widgets, post types, and post formats all allow users to fine tune their websites to display the content in the best way possible.

Today we will explore custom post types in WordPress. We will find out what they arehow or why you would use them, and to top it off we will be creating an example custom post type that you can use as a guide to creating your own. First let’s take care of some common questions about custom post types:

What is a Custom Post Type?

Custom post types are nothing more than a basic post but have different sets of parameters defined inside your code. The post type of regular posts is post, pages use page, attachments use attachment and so on. Since the release of WordPress 3.0, you can now create your own custom post types. If created successfully and the right parameters are returned you can have a customized area on your website like no other.

Why Use a Custom Post Type?

Say you want to divide up your content in more structured ways on your website. Sure, inside your blog you can define categories, tags, posts by specific authors, etc… but what if you wanted more?

Let’s say we want to add a music review section to our website. You want to be able to post a review, some album art for a featured image, the artist’s name, and possibly the genre. All of this and more can be added with custom post types.

Since our post type has to do with music reviews we can create an area of our website allow users direct access. A URL of that section would look like this: http://mysite.com/music-reviews/ with “music-reviews” being the name of our custom post type. Then within that section you can create new posts of that type resulting of a permalink URL of something advanced as: http://mysite.com/music-reviews/artist/album/. How you build the newly created section I speak of is entirely up to you which is why it’s an amazing feature of WordPress.
This may be a bit confusing at this point but I’ll explain in more detail soon when we build our own custom post type.

Creating Custom Post Type Manually

When WordPress 2.9 was introduced it offered users the ability to add custom post types to their sites for the first time. WordPress 3.0 allows users to not only add custom post types but to also tie into the admin area of the WordPress backend all with fewer lines of code. Newer conventions have allowed both users and developers to add editable option fields customized to the content being displayed on their websites.

If you’ve dabbled with PHP and know a bit about WordPress then the option is always there to add your own custom post type functionality. Currently there are two ways to go about adding the custom post type to a theme: build a plugin or add code to your theme’s functions.php file. We will be adding an example custom post type for movie reviews to a local WordPress installation. Below I will outline the steps you can take to add a custom post type to your site.

Overview

For the sake of a simple example we will be adding our new code to our functions.php file inside our theme folder. It is worth noting that this code will only be available on this particular theme installation. If you need this custom post type functionality within multiple themes then you will want to create a plugin. I won’t go into details of how to do that today but it is a rather simple and similar task to what we will be doing inside our functions.php file.

Step 1 – Register Post Type

Open your functions.php file and add the code below to it. Make sure the code is added before the closing PHP tag. I will explain the code below.

// Creates Movie Reviews Custom Post Type
function movie_reviews_init() {
    $args = array(
      'label' => 'Movie Reviews',
        'public' => true,
        'show_ui' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'rewrite' => array('slug' => 'movie-reviews'),
        'query_var' => true,
        'menu_icon' => 'dashicons-video-alt',
        'supports' => array(
            'title',
            'editor',
            'excerpt',
            'trackbacks',
            'custom-fields',
            'comments',
            'revisions',
            'thumbnail',
            'author',
            'page-attributes',)
        );
    register_post_type( 'movie-reviews', $args );
}
add_action( 'init', 'movie_reviews_init' );

Code Definitions

  • function movie_reviews_init() – Here we create a new function for our custom post type. We do this to limit conflicts with any other code inside our functions.php file. It is also a best practice when adding new code to any file like functions.php.
  • label – A plural descriptive name for the post type marked for translation. If you don’t declare a custom label, WordPress will use the name of the custom post type by default.
  • public – Whether a post type is intended to be used publicly either via the admin interface or by front-end users. WordPress sets this to false by default.Here we set it to true as we do what our custom post type to display publicly.
  • show_ui – Generates a default UI for managing this post type in the admin. You can set this to true or false. For the sake of usability, a UI in the admin area is always a good thing.
  • capability_type – Here we can declare what type of custom post type we will be dealing with. It is used to build the read, edit, and delete capabilities of a post or page. You can choose either post or page.
  • hierarchical – Whether the post type is hierarchical(e.g. page). Or in laymen’s terms, whether or not you can declare a parent page, child page, etc… of the post type. This is mainly intended for Pages. Here we declare it false so there’s no need to worry about it for our example.
  • rewrite – This rule is either true or false. The default is true so if slug argument is entered then the slug name is prepended to the posts. Our slug “movie-reviews” will be prepended to each new post of that type.
  • query_var – This rule is either true or false. It sets the post type name as a query variable.
  • menu_icon – This rule declares a custom icon for the admin area. Here we use a neat resource called dashicons that are included in WordPress already.
  • supports – This is usually an array of features the custom post type will support. Here we have quite a long list. These will tie into the admin area.
  • register_post_type($post_type, $args); – The register_post_type() is a function that WordPress recognizes as a custom post type generator. In this example it accepts two parameters which are the name of the post type itself and any arguments you would like to call.
  • add_action(‘init’, ‘movie_reviews_init’ ); – This line of code returns or calls our function so it fires and displays within our site.

Some of the explanations above may be a bit complex to wrap your head around. Never fear though, after I walk you through the process you will start to see how the code above makes our custom post type functional. If you are ever in doubt you can’t go wrong looking at the Official WordPress Codex for more information on custom post types.

Step 2 – Test

Now that we have defined our custom post type inside our functions.php file, head to your WordPress dashboard to see that we did everything correctly. You should now have a new menu item on the left side of your screen titled Movie Reviews.

Our custom post type added to the admin area of WordPress.

If you hover over the Movie Reviews section of our newly added custom post type you will see another menu which includes Movie Reviews and Add New .

View Movie Reviews or Add Movie Reviews

If you click add new you will see a familiar interface that looks just like a regular post on WordPress looks. No surprises at all but we have successfully updated our admin area. Next we need to work on including these custom post types into our site so they display on the front end. If you remember our code from earlier, the supports section in particular, you will see that when you add a new post under movies reviews all of the features listed within supports are available to you.

'supports' =>; array(
        'title',
        'editor',
        'excerpt',
        'trackbacks',
        'custom-fields',
        'comments',
        'revisions',
        'thumbnail',
        'author',
        'page-attributes',)
    );

Here we add a new Movie Review.

Step 3 – Output Movie Reviews

Now we need to add the functionality that makes what we post actually appear on the front end of our website. Let’s create a new menu that will display a navigational link to our Movie Reviews. Head to the Appearance tab in your admin area and click the menus tab. Here we call it Main Navigation. I’ll add a page called Movie Reviews as well as a couple of sample pages for demonstration purposes. Here’s what my screen currently looks like:

Notice the menu item “Movie Reviews” in the header has updated displaying what we are going for.Let’s add a new movie review. Here you will see a new post I have created which has some text, a title, and a featured image.

*A quick note about adding a new post. For my current theme I have already setup my permalinks. You should do that same to avoid conflicts from here on out. Go to the Settings area and look for permalinks. Change it to whichever you prefer. Typically the simpler the better.

Adding a new movie review

If you click view post you can see how the post appears on the site. Notice the URL. In my case I called my site dev but my URL is localhost:80/dev/movie-reviews/fargo/. In theory everything is up and running but we still want all our movie reviews to appear on the page we created called Movie Reviews like a list of our latest blog posts. If you navigate to that page you will see that it’s blank.

Our Movie Review page is blank. We need to add some code to make our custom post type to display.

In order to make our movie reviews appear on the page we will need to create a new template file.

Step 4 – Create a Custom Post Type Template

Create a new file called page-movie-reviews.php inside your theme’s folder.
Inside the folder you’ll want to add code below to tell WordPress that it is indeed a new template file.

/**
 * Template Name: Movie Reviews
 **/

Since we are already using the Divi 2.0 theme I will just copy over code from the page.php file to keep our site consistent. You can do the same for your whatever theme you are using. Just be sure to include the code above so WordPress will recognize it as a template.

Now we need to go back to the admin area and change what template we are using for the Movie-Reviews page. Our new template should appear in the dropdown under Page Attributes as Movie Reviews.

Changing our template from default to Movie Reviews

Ok so now with our template in place we need to modify some code to output our custom post type. Your page.php file should have a loop inside that looks like:

<?php while ( have_posts() ) : the_post(); ?>
// Your code
<?php endif; ?>
<?php endwhile; ?>

You will need to modify the loop by adding the following code:

<?php
 $query = new WP_Query( array('post_type' => 'movie-reviews', 'posts_per_page' => 5 ) );
 while ( $query->have_posts() ) : $query->the_post(); ?>
// Your code e.g. "the_content();"
<?php endif; wp_reset_postdata(); ?>
<?php endwhile; ?>

We have added a new query to the WordPress loop which targets our custom post type. The $query variable is used within the loop to allow for multiples to display on our Movie Reviews page. With this in place you our Movie Review page is now outputting our movie review we made earlier.

Our custom post type working after adding our code.

There’s one thing missing that I would like to output and that is the thumbnail. Your page.php file may already have this embedded in your code. You’ll know because you’ll see some images. If not then we will add one more line of code. In my case I will be adding it inside the block below:

<div class="entry-content">
 <?php
    if ( has_post_thumbnail() ) {
      the_post_thumbnail();
    }
      the_content();
    ?>
</div>

We use an if statement to first determine if a thumbnail was set from when you created your post in the admin. If it is it will display if it isn’t then WordPress will ignoring trying to look for a thumbnail. We are left with our Movie Review looking like below:

Our first movie review successfully added.

Step 5 – Add More Movie Reviews

Lets add a few more reviews. I’ll also adjust the size of our movie thumbnails from within the admin area. You’ll see now that we can propagate a collection of reviews which take up an entirely new section of our website that is completely custom. Pretty cool!

List of more movie reviews.

Finishing Up

We didn’t go deep into styling the way each custom post type is output but that’s not the goal of this tutorial. The goal was to show you the number of ways you can customize WordPress to your liking. Custom post types are extremely powerful. Our Movie Review example could be much more advanced and display things such as different categories of movies (dramas, thrillers, comedies, etc…), authors, start ratings, a custom single page for each movie review and more. There’s really no limit as to what you can achieve.

WordPress has become so powerful with newer features like custom post types. Having this power at your fingertips will allow you to build out at idea you have for a website be it Movie Reviews, eCommerce Solutions, Screencasts, or whatever you can think of. Hopefully by following along you’ve learned a little more about WordPress. This tutorial may be out of reach for some of you but I invite you to go back and follow along until you create something similar. You’ll learn by doing which for most is the best method there is.

Leave a Reply

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