Creating a custom post type using a object oriented approach?

I am looking for a good approach regarding the creation of custom post types in WordPress, using object orientation. How can I create CPTs in an clean, organized way?

Take into consideration these 3 scenarios:

  1. Plugin for distribution (5.2 compatible)
  2. Theme for distribution
  3. Own project, with total control over the PHP version and dependencies

2 Answers
2

I’ll answer scenario #3, even though it can be adapted for scenarios #1 and #2, too.

WordPress codex recommends that we create Custom Post Types (CPTs) in a plugin. Following that recommendation, I will write my answer using modern PHP, which is not meant for a distributed plugin, but rather for own projects where you have control over the PHP version running.

In the example code bellow, I will use raw examples just to give an idea of the architecture behind the creation of CPTs in a OOP manner, but in a real project, “my-plugin” would be something like “my-project”, and the creation of CPTs would be a sort of module of that plugin.

my-plugin/my-plugin.php

<?php
/**
* Plugin name: My Custom Post Types
*/
namespace MyPlugin;

use MyPlugin/CPT/Car;

// ... Composer autoload or similar here

Car::register();

my-plugin/CPT/Car.php

<?php

namespace MyPlugin\CPT;

/**
 * Class Car
 *
 * Handles the creation of a "Car" custom post type
*/
class Car
{
    public static function register()
    {
        $instance = new self;

        add_action('init', [$instance, 'registerPostType']);
        add_action('add_meta_boxes', [$instance, 'registerMetaboxes']);

        // Do something else related to "Car" post type
    }

    public function registerPostType()
    {
        register_post_type( 'car', [
            'label' => 'Cars',
        ]);
    }

    public function registerMetaBoxes()
    {
        // Color metabox
        add_meta_box(
            'car-color-metabox',
            __('Color', 'my-plugin'),
            [$this, 'colorMetabox'],
            'car'
        );
    }

    public function colorMetabox()
    {
        echo 'Foo';
    }
}

This way we have a namespace for our CPTs, and an object where we can manage it’s properties, such as registering the post type, adding or removing metaboxes, etc.

If we are accepting insertion of “Cars” from the frontend, we would use the REST API to receive the POST request and handle it in a REST Controller Class, but that is out of the scope of this answer.

Leave a Comment