Call   0208 3131682   Mon-Fri 9am-6pm

WordPress how to create a Custom Post Type (CPT) programmatically in php

By August 6, 2014 PHP, Web Design, Wordpress
Wordpress using Custom Post Type (CPT)

One of the most important developments of recent years in WordPress has been adding the ability to create our own Custom Post Types (CPT).

This allows us to duplicate and use the Post/Page interface for our own purposes ( we can also customise it to add extra fields using custom meta data).

A great example of this is Woocommerce that uses a Custom Post Type of Product for the managing (add/editing etc…) of products. In this blog post I’m going show you how to use this great feature.

Creating a Plugin with a new Custom Post Type (CPT)

I’m going to create a custom post type of Singers as in the screenshot above. I’ll set this up as a plugin so in /wp-content/plugins/singersplugin/ I created a file called plugin.php , in this file I need to register the Custom Post Type like so:

Its that simple to create if you just want a custom post type interface very similar to the existing post/page interface. As you can see I’ve called my post type ‘gb_singer’ , its good to prefix your variable/function names with something as it helps avoid conflicts with WordPress and other plugins.

How to nicely deregister our Plugin

Its also good practice to unregister stuff in your plugin when a user deactivates your plugin so you can so something like this at the end of the plugin.php file:

I’m going to expand on this example in my next few blog posts so you can see how to :

  • add fields to a custom post type
  • how to save a taxonomy on a custom post
  • how to add a featured image to a custom post type
  • how to create a tag cloud of a taxonomy related to one custom post type object

Update you can see how todo the above in my post here.

So if your interested in those things, check back at my blog soon. As always the Codex contains some great information so check it out here http://codex.wordpress.org/Post_Types

Leave a Reply