I’ve added a custom endpoint to WordPress like so:


add_action( 'rest_api_init', function () {
    register_rest_route( 'menc/v1', '/crosscat/(?P[w-]+)/(?P[w-]+)', array(
        'methods' => 'GET',
        'callback' => 'dept_cat_api',
        'args' => array(
            'dept' => array(
                'sanitize_callback' => function($param, $request, $key) {
                    return sanitize_text_field( $param );
                }
            ),
            'cat' => array(
                'sanitize_callback' => function($param, $request, $key) {
                    return sanitize_text_field( $param );
                }
            ),
        ),
    ) );
} );


function dept_cat_api( $data ) {
    $args = array(
        'post_type' => 'post',
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'crosspost',
                'field'    => 'slug',
                'terms'    => array( $data['dept'] ),
            ),
            array(
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => array( $data['cat'] ),
            ),
        ),
    );

    $posts = get_posts( $args );

    if ( empty( $posts ) ) 
        return new WP_Error( 'no_posts', 'Invalid term(s)', array( 'status' => 404 ) );

    $controller = new WP_REST_Posts_Controller('post');
    $response = array();
    foreach ( $posts as $post ) {
        $data    = $controller->prepare_item_for_response( $post, $data );
        $response[] = $controller->prepare_response_for_collection( $data );
    }

    // return results
    return new WP_REST_Response($response, 200);

}

Which cherry picks posts based on the intersection of a category and terms from a particular custom taxonomy. In my local development environment this returns the posts I expect or the 404 response where it should. On the production it returns a 500 http error and the error log reports a “PHP Fatal error: Cannot use object of type WP_REST_Response as array in /wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php on line 1554”. I’m not sure if this is a server issue or if there’s an error I can’t see. A similar function that does the same thing, with tags instead of categories, works just fine.

Read more here: PHP Fatal error: Cannot use object of type WP_REST_Response as array in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: