How to cast custom post type into separate class instead of WP_Post

I’d like to create a subclass of WP_Post and add some “model functionality” to it. How can i force WP to create objects of that child class instead of WP_Post itself, when i query for my custom post type?

Example:

Let’s assume i have two custom post types: Book and Review. Each Book can have many Reviews. On my Book, I want a method to sum up all its reviews. I’d define the following class:

class Book extends WP_Post
{
    public function reviewsSummary()
    {
        // Retrieve all reviews for $this book
        // Sum up their ratings
        // Return that sum
    }
}

Is there a way, for example when calling register_post_type(), to force WordPress into casting all posts of type “book” into my Book class instead of WP_Post?

Could look something like this:

register_post_type('book', [
    …,
    'class' => Acme\Models\Book::class
]);

2 s
2

WP_Post class in WP is final, so it explicitly forbids subclassing. It is also quite vague in practice, a lot of code around will happily take/produce post–like objects as long as they have established data structure.

It is challenging to recommend an alternative without knowing more about your specific needs. In a general and assuming use in templates the typical would be to create a template tag function that will calculate score for review post, provided to it as argument and/or current in the Loop.

Leave a Comment