WP-API v2 Custom Endpoint Response Formatting

Question

I’m trying to use a custom endpoint (basically to get a random sorting working) and am using the following code:

// Custom WP API endpoint
function theme_enable_random_api() {

    // create json-api endpoint

    add_action('rest_api_init', function () {

        // http://example.com/wp-json/random/v2/posts

        register_rest_route('random/v2', '/random', array (
            'methods'             => 'GET',
            'callback'            => 'wp_json_offers_v2__posts',
            'permission_callback' => function (WP_REST_Request $request) {
                return true;
            }
        ));
    });

    // handle the request

    function wp_json_offers_v2__posts($request) {
        // json-api params

        $parameters = $request->get_query_params();

        // default search args

        $args = array(
            'post_type'     => $parameters['type'],
            'numberposts'   => 9,
            'offset'        => $parameters['offset'],
            'post_not_in'       => $parameters['exclude'],
            'orderby'       => 'rand',
        );

        // run query

        $posts = get_posts($args);

        // return results
        return new WP_REST_Response($posts, 200);
    }

}

add_action('init', 'theme_enable_random_api');

However the response I’m getting is not the same as the response I would get from a standard call to the api.

Standard:

Custom Endpoint:

The problem really is that I can’t access the taxonomy/acf information like I can in the standard one. I’m not great with PHP so more than likely I’m not getting it properly.

Cheers.

--------------------------------------------------

>>> Share a link to this question, just copy and paste the code bellow on your web page <<<

<a href="https://www.wptricks.com/question/wp-api-v2-custom-endpoint-response-formatting/">

WP-API v2 Custom Endpoint Response Formatting</a>
0
, , evu 1 week 0 Answers 28 views 0

Leave an answer