postTypes

Intelligent custom post types. A WordPress Guide

WordPress is undoubtedly more than a blogging platform. Its a powerful content management system that allows you to easily customise and use it the the way you need. Including creating your own custom content sets.

When building plugins or themes, custom post types can be a very helpful way of organising and displaying content. For example you can use a custom post type for a product, only displayed within your store or a special post type just for customer testimonials. No matter what your need custom post types can be very helpful in getting custom content set up and organised.

Luckily WordPress has a nifty helper for you to register your custom post types. This is the register_post_type() function. The function’s parameters are as follows : name (string) ,labels (array), public (bool) and has_archive (bool).

We register our custom post type when WordPress initialises using the ‘init’ handler.

1
2
3
4
5
6
7
8
9
10
add_action(‘init’,’my_post_type’);
function my_post_type() {
         register_post_type(
            'my_custom_post',
            array(‘labels’=>'name'=>__('my custom post'),
            'singular_name'=>__('my custom posts')),
            'public' => true,
            ‘has_archive’=>true
         );
}

This is a great example of how WordPress makes it easy to customise and manage your content.

However, as many of you know, I’m a big fan of intelligent laziness, that is having code write your code. As such we can get a bit clever and create a helper class that you can simply include in your theme, or indeed plugin any time you need to set up custom post types.

First we want to set up a new class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class customPostTypes {
      function __construct($postTypes) {
        $this->customPostTypes = $postTypes;
        add_action('init', array($this,’getPostTypes’));
      }

      function getPostTypes() {
        foreach($this->customPostTypes as $postType => $postTypeInfo) {
           $this->createPostType($postType,$postTypeInfo);
        }
      }
      
      private function createPostType() {}
};

new customPostTypes($postTypes);

Here we are creating the customPostTypes class. Within the __construct function (that gets called when we create a new instance) we set the instances post types to our input variable (explained below) and bind the setting class to WordPress initialisation.

Note: when using wp hooks in a class pass an array as the second parameter, the first member is ‘$this’ and the second is the name of the child function.

Next we loop over each of our desired custom post type and call the createPostType function.

Setting up our input variable:
Now we have our base class set up lets set up our input variable, this is where we will be setting the information for our post types. Each post type might have different settings, especially when it comes to support, so we have to account for that, alternatively you may just want to create a standard custom post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//For standard custom post types set up your input variable as follows :
$postTypes = array(‘postType1’,’postType2’);

// For more customised post types set up your input variable like this:
$postTypes = array(
"postType1" => array(
                  "supports"=>array('title', 'editor','thumbnail'),
                  "public"=>false,
                  "has_archive"=>true
),
"postType2" => array(
                  "supports"=>array('title', 'editor','thumbnail'),
                  "public"=>false,
                  "has_archive"=>true),
"postType3",
);

Note that postType3 has no additional information. We will code our ‘createPostType’ function to handle all inputs allowing us to mix and match as we please.

Our dynamic createPostType function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private function createPostType($postType,$info) {
        $public = (isset($info["public"])) ? $info["public"] : true;
        $supports = (isset($info["supports"])) ? $info["supports"] : array( 'title', 'editor', 'author', 'thumbnail', 'excerpt' );
        $archive = (isset($info["has_archive"])) ? $info["has_archive"] : true;

        // Check if info set
        $name = (gettype($info) == "array") ? $postType : $info;

        // Set the name and singular name
        $labels = array( 'name' => __( $name.'s' ), 'singular_name' => __( $name),'add_new_item'=> __("Add new ".$name) );

        // Set the post type arguments
        $arguments = array( 'labels' => $labels ,
          'public' => true,
          'has_archive' => true,
          'supports' => $supports
          );
         
        // Finally register the post type
        register_post_type( $postType.'s', $arguments);
}

Firstly we set our post type settings. If the post type has advanced settings attached (within a second array) we set our settings (public,supports and achieve) to the information passed in. Otherwise we set them up within the function. Similarly if the info passed in is an array, rather than a string, it means that advanced settings have been set for this post type and we use the array key as the post name.

Using this sort of structure allows us to pass in an array of mixed values. (either single or array value)

Custom post types are a powerful tool in any WordPress developers tool box, now you can confidently add it to yours.

The full class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* 
   lazyCustomPostTypes : easily add custom post types to your wordpress theme or plugin. 
   created by : Codeanthology
   url: codeanthology.com/
*/
class customPostTypes {
      function __construct($postTypes) {
           $this->customPostTypes = $postTypes;
           add_action('init', array($this,'getPostTypes'));
      }
    
     function getPostTypes() {
        foreach($this->customPostTypes as $postType => $postTypeInfo) {
            $this->createPostType($postType,$postTypeInfo);
        }        
      }
    
      private function createPostType($postType,$info) {
          $public = (isset($info["public"])) ?  $info["public"] : true;
          $supports = (isset($info["supports"])) ? $info["supports"] : array( 'title', 'editor', 'author', 'thumbnail', 'excerpt' );
          $archive = (isset($info["has_archive"])) ? $info["has_archive"] : true;
          
          // Check if info set
          $name = (gettype($info) == "array") ? $postType : $info;
          
          // Set the name and singular name 
          $labels = array( 'name' => __(  ucfirst($name.'s') ), 'singular_name' => __( $name));
          
          // Set the post type arguments
          $arguments = array( 'labels' => $labels ,
                              'public' => true,
                              'has_archive' => true,
                              'supports' => $supports
                            );          
          
          
          register_post_type( $postType.'s', $arguments);
      }
}

new customPostTypes($postTypes);

What is your experience with custom post types? Is there anything you do differently? Join the discussion below.

Rory K

Rory Kermack is a professional programmer, interactive designer, and entrepreneur. Working with the #iot, #hybridapps, #webrtc & #reactjs. Senior dev & main contributor of codeanthology.