Miscellaneous REST API improvements in WordPress 6.1

Search REST resources by ID across subtypes

WordPress 6.1 includes an enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature. to the search controller, #56546, which makes it possible to retrieve a term or post object over the REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. without knowing anything but that resource’s ID and object type.

get_post can retrieve a post of any post type so long as you know the post’s numeric ID, and get_term can retrieve a term from any taxonomyTaxonomy A taxonomy is a way to group things together. In WordPress, some common taxonomies are category, link, tag, or post format. https://codex.wordpress.org/Taxonomies#Default_Taxonomies.. Because REST objects are segregated by post type-specific endpoints, however, there has not been a clear way to get a Post with ID 78 if you don’t know whether it is a page, post, or my-cpt.

The coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. /search endpoint now supports ?include and ?exclude parameters which take a list of IDs, and limit results to posts matching those IDs.

Examples:

  • To get post 78 when you don’t know its post type,
    • /wp/v2/search?include=78
  • To get posts 78 and 79 only if they are in the page post type,
    • /wp/v2/search?include=78,79&subtype=page
  • To search posts excluding post 78,
    • /wp/v2/search?exclude=78
  • To get term 87,
    • /wp/v2/search?type=term&include=78
  • To get term 87 only if it is a categoryCategory The 'category' taxonomy lets you group posts / content together that share a common bond. Categories are pre-defined and broad ranging.,
    • /wp/v2/search?type=term&include=78&subtype=category
  • To search terms excluding terms 87 and 88,
    • /wp/v2/search?exclude=87,88

The search endpoint supports the _embed metaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress. parameter, so developers can therefore use the search endpoint to retrieve a full post or term response object in one request knowing only those object’s IDs.

As an example of how this could be used, imagine a custom blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. which relates to a specific post. As of WordPress 6.1 developers can implement that block knowing only the related post’s ID, and could then create a hook to search for that post by ID and retrieve it using the Block Editor’s existing entity system:

/**
 * Dictionary of requested items: keep an in-memory list of the type (if known)
 * for each requested ID, to limit unnecessary API requests.
 */
const typeById = {};
​
/**
 * Query for a post entity resource without knowing its post type.
 *
 * @param {number} id Numeric ID of a post resource of unknown subtype.
 * @returns {object|undefined} The requested post object, if found and loaded.
 */
function usePostById( id ) {
    const type = typeById[ id ];
​
    useEffect( function() {
        if ( ! id || typeById[ id ] ) {
            return;
        }
​
        apiFetch( {
            path: `/wp/v2/search?type=post&include=${ id }&_fields=id,subtype`,
        } ).then( ( result ) => {
            if ( result.length ) {
                typeById[ id ] = result[0].subtype;
            }
        } );
    }, [ id ] );
​
    return useSelect( function( select ) {
        if ( ! id || ! type ) {
            return undefined;
        }
        return select( 'core' ).getEntityRecord( 'postType', type, id );
    }, [ id, type ] );
}

Pretty-printing REST endpoint JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. responses

WordPress 6.1 also introduces support for returning pre-formatted JSON from the REST API. #41998 lets developers request formatted JSON using a new _pretty query parameter or a filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output., particularly useful when querying via curl or other tools which do not provide an option to format responses.

To format the JSON returned from a specific endpoint request, append the ?_pretty query parameter to the endpoint URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org.

To instruct WordPress to pretty-print all REST response bodies, a developer can use the rest_json_encode_options filter:

function myproject_pretty_print_rest_responses( $options ) {
        $options |= JSON_PRETTY_PRINT;
​
        return $options;
}
add_filter( 'rest_json_encode_options', 'myproject_pretty_print_rest_responses', 10 );

A developer or site owner may also disable pretty-printing globally using the same filter:

function myproject_disable_rest_pretty_printing( $options ) {
        $options &= ~JSON_PRETTY_PRINT;
​
        return $options;
}
add_filter( 'rest_json_encode_options', 'myproject_disable_rest_pretty_printing', 10 );

Filters are applied after, and can override, the _pretty query parameter.

Thanks to @spacedmonkey for peer review.

#core-restapi, #dev-notes, #dev-notes-6-1, #rest-api