How to create WordPress custom post type programmatically

Do you want to publish custom post types on your site? We’ve got you covered. In this guide, we’ll teach you how to create WordPress custom post type programmatically with a bit of code.

Initially, WordPress was created to publish posts. However, after all these years, WordPress is much more than a platform to publish posts. Nowadays, it’s the most complete web solution that powers nearly 40% of all websites.

Even though it has incorporated many functionalities, post publishing is still one of the best ways to attract users to your site and keep them engaged. WordPress offers default post types but if you want to customize your site and make it unique to stand out from your competitors, creating custom post types can be a good solution.

In this tutorial, we’ll show you how to create and publish WordPress custom post types programmatically. Before jumping into that, let’s better understand what exactly custom post types are and when you should use them.

What is a custom post type?

Custom post types are types of content. WordPress comes with several post types by default. Posts and pages are the most famous ones but there are others:

  • Posts
  • Pages
  • Attachments
  • Navigation Menus
  • Revisions
  • Customized CSS
  • Changesets

Most users use the first five types but there are other types. Actually, you are probably using some of them without knowing that they are custom post types.

The best example of a custom post type is WooCommerce products. When you activate WooCommerce for the first time, the plugin creates a custom post type called “Products”. Once you start creating products, they are published as a product post type, featuring all the enhancements that WooCommerce offers.

Even though these post types are not called custom, you can create your post types the same way that WooCommerce does and give them the name you want. For example, events, listings, schedules, lessons, portfolios, and profiles can be post types names that will be useful for specific websites.

All in all, custom post types are a new type of post that users can create according to specific requirements to customize their website.

Why and when should you use a custom post type?

Custom post types (CPT) can be very different depending on how they are built, so you can use them to achieve all kinds of solutions.

You can use custom post types when:

  • You are going to post regularly some specific kind of information that you can’t publish using the default posts type
  • Need to differentiate a certain type of posts from the standard ones
  • Need to change the behavior of some type of posts
  • Want to customize the post features, publishing process, and elements or apply some special feature to them

As a general rule, you should use CPT on a WordPress site when you need different kinds of posts with their features or custom behavior.

Custom post types are different from the default post types, so they require a special treatment without having to overwrite the default post type features. This is a big advantage when you need different post types because you can create a custom post type from scratch that will exactly meet your requirements.

Now that we better understand what they are and when to use them, let’s see how to create custom post types.

How to create WordPress custom post type programmatically

In this section, we’ll show you how to create a custom post type in WordPress with an example. Before you start, make sure you backup your site and create a child theme if you don’t have one already.

In your dashboard go to Appearance > Theme Editor, open the functions.php file of the child theme on the right column and paste the following script. It will register a custom post type called movies.

function QuadLayers_custom_post_type() {
// Set UI labels for Custom Post Type
    $labels = array(
        'name'                => _x( 'Movies', 'Post Type General Name', 'storefront' ),
        'singular_name'       => _x( 'Movie', 'Post Type Singular Name', 'storefront' ),
        'menu_name'           => __( 'Movies', 'storefront' ),
        'parent_item_colon'   => __( 'Parent Movie', 'storefront' ),
        'all_items'           => __( 'All Movies', 'storefront' ),
        'view_item'           => __( 'View Movie', 'storefront' ),
        'add_new_item'        => __( 'Add New Movie', 'storefront' ),
        'add_new'             => __( 'Add New', 'storefront' ),
        'edit_item'           => __( 'Edit Movie', 'storefront' ),
        'update_item'         => __( 'Update Movie', 'storefront' ),
        'search_items'        => __( 'Search Movie', 'storefront' ),
        'not_found'           => __( 'Not Found', 'storefront' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'storefront' ),
    );
// Set other options for Custom Post Type
    $args = array(
        'label'               => __( 'movies', 'storefront' ),
        'description'         => __( 'Movie news and reviews', 'storefront' ),
        'labels'              => $labels,  
        'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),     
        'taxonomies'          => array( 'genres' ),     
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 5,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'post',
        'show_in_rest' => true, 
    );
    // Registering your Custom Post Type
    register_post_type( 'movies', $args );
}
add_action( 'init', 'QuadLayers_custom_post_type', 0 );

After pasting the code, a new tab called Movies will appear on your WordPress admin dashboard.
Create Custom Post type programatically

If you open it, you will see that the post editor is the same as default post types, because we have set the same arguments for the post editor screen. So how do we know that it is the custom post type editor? Because on the URL and title of the page, you can see the Movies post type.

Add custom post type

Now that you saw the end result, let’s analyze the code, so you can better understand what each section does.

Code explanation

We’ve just seen how to create a WordPress custom post type programmatically. But that’s only half of what you have to know. If you want to create your own post types, you need to customize the code. And for that, you need to understand what each part of the snippet does.

We use the wp_init() hook to ensure that our function runs a single time: when WordPress initiates. In our QuadLayers_custom_post_type()function, there are three parts.

1) Labels

These are a set of strings that the theme will use on different admin and frontend pages. This is set on a single array:

$labels = array(
'name' => _x( 'Movies', 'Post Type General Name', 'storefront' ),
);

2) Options

These are some predefined options that define the behavior and some other features of our custom post type (movies).

Each option is a specific instruction that will define how our custom post type will act. The most relevant ones are:

  • ‘supports’:  It defines which components will be used on the post editor
  • ‘taxonomies’: You can apply one or more existing categories or custom categories to all CPTs registered on the current function
  • ‘hierarchical’: Posts can’t have parent content and this will differentiate the CPT from pages.  Set this to true if you want to publish a custom page instead of a custom post type
  • show_in_admin_bar’: Displays the CPT tab on the WordPress admin dashboard

For the complete list of all the arguments and their description, check out this documentation.

3) Custom Post Type registration

The WordPress function register_post_type() will finally register our new custom post type and set it so it’s ready to use.

Now you better understand the code, you can start publishing your custom post types. But apart from publishing them, you will want to display your CPT somewhere. Let’s see how to do that.

How to display custom post types in WordPress

So far, we’ve seen how to create a custom post type programmatically in WordPress. After publishing it, you have to decide where you’re going to display it.

There are several ways in which you can print a CPT on the front end. You can display a full list of specific custom post types on another post, page, sidebar, or any other place that you want.

In the following sample script, we are going to create a custom shortcode to display all the custom post types we created using the previous function on a new page.

The following script will create a shortcode called Movies, that will print all the movies that we add to our CPT on any page where we add the shortcode.

add_shortcode('movies', 'QuadLayers_display_cpt_shortcode');
function QuadLayers_display_cpt_shortcode(){
    $args = array( 'post_type' => 'movies', 'posts_per_page' => 10 );
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
    $c= the_title( sprintf( '<h2 class="entry-title">', esc_url( get_the_title() ) ), '</h2>').
    '<div class="entry-content">'.
    the_content().
    '</div>';
endwhile;
wp_reset_postdata();
else:
$c = 'Sorry, no posts matched your criteria.';
endif;
return $c;
}

So if you place the shortcode on a page:

shortcode to display CTP

You will see the result:

custom post type with shortcode

Conclusion

In summary, we’ve seen that, by default, WordPress includes some post types but you can add custom post types depending on your requirements to customize your site.

In this guide, we’ve shown you how you can create a WordPress custom post type programmatically. We’ve analyzed the snippet and described each section, so you can customize it and use it on your site. Additionally, we’ve seen how to create a custom shortcode that allows you to display your custom post types anywhere on your site.

Have you tried creating custom post types on your site? Let us know your experience in the comments section.

To customize other areas of your site, check out the following tutorials: