Search code examples
phpwordpresscustom-post-type

How to make WordPress turn my posts into objects of a different class than 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
]);

Solution

  • I am not sure, but maybe this is a way for that what you want:

    Look here at line 3617 -> query.php

    // Convert to WP_Post objects
    if ( $this->posts )
        $this->posts = array_map( 'get_post', $this->posts );
    
    if ( ! $q['suppress_filters'] ) {
        /**
        * Filter the raw post results array, prior to status checks.
        *
        * @since 2.3.0
        *
        * @param array    $posts The post results array.
        * @param WP_Query &$this The WP_Query instance (passed by reference).
        */
        $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
    }
    

    Maybe you can use the filter hook apply_filters_ref_array and run your own function if the post type is a book.

    // in your filter function
    if ( book ) {
       return array_map( 'get_book', $posts );
    }
    return $posts;