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
]);
WP_Post
…