Elegant Themes Blog

Stay up to date with our most recent news and updates

Creating Custom Post Types In WordPress

Posted on June 23 by in Tips & Tricks | 50 comments

Creating Custom Post Types In 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 are, how 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.

Can I Just Use A Plugin?

Sure! If you’re not versed in editing your site’s code or need something fast, there are plugins available to help you with creating custom post types. Many are easy to setup and offer amazing results. Some allow you to customize your admin area which helps the user experience for yourself as well as provides the content you want to display to your users. Our collection of themes include assistance with this functionality as well. Below are a list of a few I recommend trying.

Custom Post Type UI

This plugin provides an easy to use interface to create and administer custom post types and taxonomies in WordPress. This plugin is created for WordPress 3.x. The plugin simply creates the types. You will need to add them to the theme yourself.

plugin-custom-post-type-ui

Plugin: Custom Post Type UI

Types lets you customize the WordPress admin area by adding content types, custom fields and taxonomy. You will be able to craft the WordPress admin and turn it into your very own content management system.

Plugin : Types

Plugin: Types

Adding Your Own Custom Post Type

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 using the new Divi 2.0 Theme from our Elegant Themes library. 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.

dashboard-custom-post-type-added

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 .

movie-reviews-add

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',)
    );
add-new-review

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:

menu-setup

Here we setup our menu structure for our primary navigation.

So if we head to our front page you should see something similar. Remember I am using the new Divi 2.0 theme. At the moment I haven’t customized it much. 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.

movie-review

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:8888/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.

movie-reviews-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.

change-template

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.

movie-reviews-output

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:

movie-review-complete

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!

movie-view-list

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.

Elegant Themes is not affiliated with the artwork and Movie titles displayed in this tutorial. They are used only by example.

50 Comments

  1. I’ve always wanted to learn how to create custom post types as I figured there would come a time when I needed something I couldn’t find in a theme or plugin. Thanks for breaking it down in a simple way.

  2. Great tutorial! Thanks very much Andy!

    Great stuff, keep em coming!

      • I do have one question, and sorry if you covered this and I missed it, but is this tutorial specific to Divi 2.0 or will this work with any WordPress theme?

        Thanks again!

        -Kraymer

        • Hey Kraymer, This works on any theme. I used Divi 2.0 for example purposes only.

  3. Great article! One resource I use quite a lot for custom types and taxonomies, and highly recommend: http://generatewp.com/

  4. Hey Andy. Excellent write-up. Great job explaining the details. Personally, I think using a plugins like CPT UI (my favorite) or Types is usually the best way to go for a couple reasons:

    1. They’re plugins so your custom post types will automatically be theme independent. I’d be placing the code in a plugin for this reason anyway.

    2. It makes things so much easier and basically fool-proof. I have no problem messing with the code to add a CPT but with one of the plugins I know there isn’t any chance for syntax errors. Also, I can have a CPT created within just a couple minutes, quicker than with code. One cool thing about Custom Post Types UI is that you can export the code to register and add a CPT if, for example, you’re adding the CPT to a client’s site and don’t want to install the plugin.

    Anyway, nice job on the post!

    • Hi Ren, Thanks a lot. I agree creating a custom plugin is the smart way to go for this. For this post I was introducing the concept of a custom post type. Maybe for a future post I’ll expand on this model and show how to create a plugin based of the custom post type functionality. Thanks again!

      • Hello Andy,

        I would love a post on how to create a plugin for custom post types. I have instructors that need to list their classes on their WordPress sites where these classes managed in instructifyme.com. With a plugin I can have the instructors ‘sync’ a class over to WordPress where it would populate the custom post type. Obviously the plugin would need to do much more than what you’ve show here, since it needs to sync, but your plugin post would be a great start.

        Thanks for the great post!

  5. I may embark on a journey to create a ton of different custom post types for divi 2.0 as a child theme. As well as add some more modules.

    This post definitively pointed me in the right direct, thanks!

  6. Is Elegant Themes looking at creating a plugin to display custom post types? THAT is something I would pay extra for, even though I already have a Developer license.

    • Wp-types offers this in a plug-in called views.

  7. Nice review,
    I do make use of custom post types in almost all of my projects.

    Wp-Type is an ideal plug-in for easy creation of custom post types, custom post fields and taxonomies.

    Although not free, i would advice to combine wp-types with wo-views for easy creation of post templates, post archives and custom views, for displaying post data.

  8. Great article Andy…I would like to know more. Thanks

  9. This is sooo awesome that I have to drop by and leave a comment. I’ve been looking for resources on how I can pull custom posts off and you did a great Job, Andy. Thank you!

  10. Great tutorial, thank you so much. Is there a way to use the Divi Builder with the custom post types?

    • Hi Al,

      Thanks for the comment. I believe the functionality exists but might need a little tweaking to create completely custom post types. Maybe I’ll cover this in an upcoming article.

      • I’d like to know what “little tweaking” means as custom post types are common for me and it would be awesome to use the Divi Builder from Divi 2.0.

  11. This goes as one of the best tutorials on this blogs, and comes when I really needed it. Thanks ! :)

  12. Great article, but aware all this features and functionality. Useful article for beginner,

    • Definitely a good starting point for those new to custom post types and WordPress.

  13. Nice articles. I prefers creating post type with code not using any extra plugin.

    • Thanks Ashmita, With the latest version of WordPress it takes a lot less code to customize your custom post types so I agree with you. I also will say plugins are great if you want to take advantage of the functionality across multiple themes rather than modifying multiple files. Something to keep in mind!

  14. Bravo! You got me right on Step No4! Thank you very much. More of this post will reduce our bug in the support area. Also, how will you style it to look professional like the styling in Divi 2.0 audio custom post format. And Please may I ask if you can post a tutorial on how to integrate a long bar custom search in page of Divi or how to integrate Google Search bar engine in page of Divi?

    Thanks Andy.

    • Hi bb,

      Any styling can be done with CSS whether it’s using predefined styles for the Divi 2.0 theme or your own custom ones. I’ll consider the request for the tutorial you speak of. Thanks for the comment!

  15. Great tutorial! Thanks for the article.

  16. Its Grat and Simple. Its Look Hard to do but you Describe It in very Simple Way . Thanks! :)

  17. Awesome post/tutorial. Thanks.

  18. Hey thank you for this post! Question: what if I want my custom post type to appear in the home page (and slider) of an elegant theme exactly like a simple post? Thanks

  19. Hello. How I can add Page Builder in my CPT? Thx…

    • I’ve got everything working except for the page builder as well. Actually, mine doesn’t have the template drop down under attributes either but as long as I can get the page builder working that part isn’t as important :)

  20. Hi Andy,

    this sounds like a great way to expand WordPress functionalities. When I tried to implement the code into my function.php my installation crashed though.
    What does “Make sure the code is added before the closing PHP tag” mean? Adding the new code before the last “<?php" tag ?
    Thanks for your help,
    Robin

  21. Great write up and good resource for the user customizing their own theme. I champion using a plugin though in case you want to switch themes and still have access to your data. Custom Post Type UI is one of the better ones.

  22. What about the pagination? i tried it in a blank page themes in a child themes, i got no pagination

  23. Great article , really interesting!!
    There is a way to see our custom post type in projet, portfolio of divi2?
    Thank you

  24. HI! — Really enjoyed your tutorial. Best tutorial I have read yet. Thanks so much.

    I have a question… Im wondering why you set up the CPT with capability_type as “post” and non hierarchical but the you save the page as a page?? Why not archive or… IDK. Probably simple but I’m a newbie and have been struggling trying to get WP to pull archive.php instead of page.php. Maybe it shouldn’t be….

    Also, I stumbled across this article after reading another article convincing me to do away with the CPT IU plugin… after reading peoples pro-plug-in comments here I need help! Plug in or not to plugin? I am working on my companies website and don’t anticipate changing themes… However I am in the middle of another side-job and I can see that client wanting to change themes.

    • Hi eileen

      It depends upon requirement whether to go for hierarchical type or non hierarchical.

      Here user wanted a list of Movies, so a non hierarchical would be better.

      About page.php…

      this might be little confusing for you, but that’s the right way to do this. You need to create a page template to output List of Movies through WP_Query.

      Dont get confused in this, Its just a piece of code and has nothing to do with page and post custom post types.

      use plugins to create custom post types if you are not in touch with wordpress codex.

  25. Great post! Really helped me get my head wrapped around custom post types.
    Thanks!

  26. Thanks for the great tutorial Andy. I just went through it and had a few questions:
    1. You mentioned that “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 do you do that? I get the http://mysite.com/music-reviews/ portion, but how about the /artist/album/ portion?

    2. Even before I create the Music Reviews page, I already get content if I visit http://mysite.com/music-reviews/, because movie-reviews is the slug you chose for the custom Post Type. Did I do something wrong?

    Thanks!

  27. Love custom Post type… Nice tutorial.
    How can i create sets of category for each custom post type?

    Thanks

  28. Hello, I’m creating CPT using the first plugin, and it’s pretty awesome. Just one thing I cannot figure out, is how to enable Page Builder for these new Custom Post Types? I need Page Builder enable all along the website. Is this possible?

  29. I’m using PODS to create a custom post type and I have it displaying a single item OK, but it’s displaying the page with a sidebar. I want to have it be full page, but PODS isn’t letting me specify the ET type for the page. Is there a way I can “simulate” that this was selected before I call get_header()?

    Or is there some other meta data that I have to make sure get’s saved with the new content?

    Thanks.

Leave a Reply

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

Current ye@r *

Join 253,319 Happy Customers And Get Access To Our Entire Collection Of 87 Beautiful Themes For The Price Of One

We offer a 30 Day Money Back Guarantee, so joining is risk-free!

Sign Up Today