• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Ani's Webdev Blog

A learning diary of website development

  • Home
  • Demo
    • Ajax Contact Form
  • WordPress
  • Front-end
  • Backend

[WordPress] Create custom post type programmatically

Modified on: March 13, 2023

In this article, let’s talk about custom post types. What are they, why we need them, how to create them programmatically, and have a look on its anatomy in case you want to have custom design templates for the pages generated by the custom post type.

Table of contents

  1. What is custom post type and do I need it?
    1. How to add custom post type programmatically in WordPress
      1. Creating custom taxonomies programmatically
        1. Creating template files for custom post type
          1. Archive page
            1. Single page
              1. Taxonomy page
              2. How to query the custom post type
                1. Visually: how it looks like in WordPress admin dashboard

                  What is custom post type and do I need it?

                  By default, WordPress gives us several post types: page, post, attachment, navigation menu, revisions, custom css and changesets. Among them, Pages and Posts are probably the most recognizable ones.

                  You would probably asks yourself several times, “Do I need a custom post type? Can things be ok with just using pages or posts?” If that question still hanging on your head, I would suggest to create custom post type if:

                  • You need to filter and query the post type articles separately from other post types, and have to do it frequently, via WordPress WP_Query or via Rest API endpoints
                  • It needs custom taxonomies which should be filtered and queried, too
                  • You don’t mind creating a bunch of templates to support the custom post type’s single page, archive page and taxonomies page. It’s optional though, because without them, WordPress will use the style from the current theme. But in many cases you would want to have custom designs for those generated by custom post type, and you would need to know how to do it

                  In the other side, if you just want to post articles which have some extra fields that does not yet have in Posts and Pages, then it’s easier to create custom meta fields and attach to posts / pages instead.

                  Notices:

                  • There will be a difference in slugs. If you use WordPress built-in Pages and Posts, the slug of a single article / page can be http(s)://domainname.com/{name-of-the-article}. If you access a a custom post type single page, it will be http(s)://domainname.com/{custom-post-type-base}/{name-of-the-article}. So it would somehow affect SEO if think about how the slug that include keyword should be close to the domain name.
                  • The custom post type will be saved together with other post types in wp_posts table

                  If now you already decided that you need custom post types, not custom meta fields, then read on!

                  How to add custom post type programmatically in WordPress

                  If you don’t want to touch the code, it’s fine to just use any plugin to do this. But, creating the custom post type programmatically is pretty easy. And below is how you can do it.

                  To make things easier to imagine, let’s say we have a private clinic website and would need to create the new custom post type to display doctor profiles.

                  Warning

                  As WordPress suggests, do not add the code in your theme’s file. That way, if you switch themes, you will lose the custom post type. But, if you create a theme by yourself and do not have a plan to change it in the whatsoever future, then the code can be in your theme.

                  HTML

                  This WordPress page about custom post types explains the parameters very well so please read it.

                  Warning

                  You don’t need to explicitly set all parameters, but you must explicitly set public, or else your post type won’t show up in the Admin Dashboard.

                  Here, let’s go through some useful one:

                  • has_archive: can be set to false if you want to disable the front page http(s)://domainname.com/doctor/
                  • supports: by default, WordPress will give ‘title’, ‘editor’, ‘comments’, ‘revisions’, ‘trackbacks’, ‘author’, ‘excerpt’, ‘page-attributes’, ‘thumbnail’, ‘custom-fields’, and ‘post-formats’. Only some of them are necessary, so we only include here title (doctor name), editor (description), thumbnail (probably a photo).
                  • rewrite, slug: rewrite the base that is used in http(s)://domainname.com/{base}/{single-record-slug}. It is useful if you want it to be different language than “doctor” – the custom post type name that WordPress will use.
                  • dashicons: the icon that shows up in WordPress dashboard. Check for a list of dashicons from here.

                  Creating custom taxonomies programmatically

                  What’s custom post types without custom taxonomies? So let’s create one also.

                  Supposed that we need a categorized page for doctors based on their expertise (cardiologists, dermatologists, dentists, allergists).

                  And so when user visits page http(s)://domainname.com/expertise/cardiologists for example, they will see a list of doctors who can solve your blood and heart issues.

                  To create custom taxonomies programmatically, just continue with the function ak_create_doctor_profiles_cpt(), add the function register_taxonomy() below the register_post_type() function:

                  HTML

                  Again, WordPress Codex provides really helpful info about how to set your own config. They are quite straightforward, but here is one tricky part if you haven’t noticed: the public parameter will affect other parameters like publicly_queryable, show_ui and show_in_nav_menus. So if you would like to change the visibility of the taxonomy, use the combo carefully.

                  Creating template files for custom post type

                  Before going deeper, let’s have a look of the anatomy of custom post type pages. In our “doctor” example, it will be like:

                  • Archive page: can be accessed via http(s)://domainname.com/doctor/
                  • Single page: for every record that you create with the custom post type, it can be seen via http(s)://domainname.com/doctor/{single-record-slug}/
                  • Taxonomy page: for every term (e.g cardiologists, dermatologists, dentists, allergists) that is created, the page that collects all records that had the term can be accessed via http(s)://domainname.com/expertise/{term-slug}

                  Now let’s see how you can create and map the correct template to each of the types mentioned above.

                  Information

                  It is not mandatory to create custom files for these pages. If you don’t make, WordPress will get the template from your current theme’s design, or more specific, from these files: archive.php, single.php and taxonomy.php.

                  Archive page

                  To make a custom archive page, create a PHP file and name it archive-doctor.php. WordPress system will automatically detect it and load it when your archive loads.

                  Single page

                  Similar to the way to create archive page, just create single-doctor.php and implement your design there.

                  Taxonomy page

                  The name for taxonomy page that WordPress can map the template is taxonomy-expertise.php. See more from here.

                  How to query the custom post type

                  WP_Query() and get_posts() both have a parameter that you can filter the post type to return. Here is the examples from both:

                  For WP_Query()

                  HTML

                  For get_posts()

                  HTML

                  Visually: how it looks like in WordPress admin dashboard

                  So here’s how you can see the newly created custom post type.

                  creating custom post type programmatically wordpress

                  That’s it! Simple as life. Bye and see you in the next article!

                  Filed Under: Wordpress, Wordpress Plugins, WordPress Themes Tagged With: php

                  Recent posts

                  [WordPress] Let’s Make Plugin E01: A Simple View Count Plugin

                  [WordPress] Create custom post type programmatically

                  [WordPress] Open Images in Posts into Lightboxes On Clicks (Without Plugins)

                  Reader Interactions

                  You are here: Home / Wordpress / [WordPress] Create custom post type programmatically

                  Leave a Reply Cancel reply

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

                  Primary Sidebar

                  Hi! I am a Vietnamese coder living in Oulu, Finland. Currently I am working with PHP, MySQL, HTML, CSS, and JavaScript. This blog is my learning diary, in which I share knowledge from my own experience or research. Hopefully you can find something useful here and don’t hesitate to open a discussion or leave a feedback!

                  FOLLOW MY BLOG

                  Thank you for visiting this website! I hope you find something useful here :). Contact me by email: anh@anhkarppinen.com.