1

if I do /wp-json/wp/v2/tags I only can get first 10, and seems the adding per_page=0 no longer work on it for getting actually all tags.

Anyone knows how to actually get all the tags with wp-api 2.0?

1 Answer 1

4

If we look at the WP_REST_Controller::get_collection_params() method, we can see the minimum is 1 and the maximum is 100:

'per_page' => array(
    'description'        => __( 'Maximum number of items to be returned in result set.' ),
    'type'               => 'integer',
    'default'            => 10,
    'minimum'            => 1,
    'maximum'            => 100,
    'sanitize_callback'  => 'absint',
    'validate_callback'  => 'rest_validate_request_arg',
),

If we check the CHANGELOG.mdfile we find this:

- Enforces minimum 1 and maximum 100 values for `per_page` parameter.

(props @danielbachhuber,
[#2209](https://github.com/WP-API/WP-API/pull/2209))

There we see that this is related to issue #1609 where @rmccue comment is:

You should be able to filter rest_endpoints and change the maximum value there. This should potentially be easier, but ideally you shouldn't be changing this.

The rest_endpoints filter is applied within the WP_REST_Server::get_routes() method:

/**
 * Filters the array of available endpoints.
 *
 * @since 4.4.0
 *
 * @param array $endpoints The available endpoints. An array of matching regex patterns,
 *                         each mapped to an array of callbacks for the endpoint. 
 *                         These take the format
 *                         `'/path/regex' => array( $callback, $bitmask )` or
 *                         `'/path/regex' => array( array( $callback, $bitmask ).
 */
 $endpoints = apply_filters( 'rest_endpoints', $this->endpoints );

As an example we could try:

/**
 * Change the maximum of per_page for /wp/v2/tags/ from 100 to 120
 */
add_filter( 'rest_endpoints', function( $endpoints )
{
    if( isset( $endpoints['/wp/v2/tags'][0]['args']['per_page']['maximum'] ) )
        $endpoints['/wp/v2/tags'][0]['args']['per_page']['maximum'] = 120;

    return $endpoints;  
} );

Another approach could be through the rest_post_tag_query filter:

/**
 * Fix the per_page to 120 for the post tags query of get_terms()
 */
add_filter( 'rest_post_tag_query', function( $args, $request )
{
    $args['number'] = 120;
    return $args;
}, 10, 2 );

where you might want to adjust this further to your needs.

Note that this default restriction on per_page could "protect" your server, from hight load, if your install has large number of terms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.