WP_REST_Block_Directory_Controller::prepare_item_for_response() WordPress Method

The prepare_item_for_response() method is used to prepare a block for use in a REST response. This method is called by the get_item() and get_items() methods.

WP_REST_Block_Directory_Controller::prepare_item_for_response( array $item, WP_REST_Request $request ) #

Parse block metadata for a block, and prepare it for an API response.


Parameters

$item

(array)(Required)The plugin metadata.

$request

(WP_REST_Request)(Required)Request object.


Top ↑

Return

(WP_REST_Response|WP_Error) Response object on success, or WP_Error object on failure.


Top ↑

Source

File: wp-includes/rest-api/endpoints/class-wp-rest-block-directory-controller.php

	public function prepare_item_for_response( $item, $request ) {
		// Restores the more descriptive, specific name for use within this method.
		$plugin = $item;

		// There might be multiple blocks in a plugin. Only the first block is mapped.
		$block_data = reset( $plugin['blocks'] );

		// A data array containing the properties we'll return.
		$block = array(
			'name'                => $block_data['name'],
			'title'               => ( $block_data['title'] ? $block_data['title'] : $plugin['name'] ),
			'description'         => wp_trim_words( $plugin['short_description'], 30, '...' ),
			'id'                  => $plugin['slug'],
			'rating'              => $plugin['rating'] / 20,
			'rating_count'        => (int) $plugin['num_ratings'],
			'active_installs'     => (int) $plugin['active_installs'],
			'author_block_rating' => $plugin['author_block_rating'] / 20,
			'author_block_count'  => (int) $plugin['author_block_count'],
			'author'              => wp_strip_all_tags( $plugin['author'] ),
			'icon'                => ( isset( $plugin['icons']['1x'] ) ? $plugin['icons']['1x'] : 'block-default' ),
			'last_updated'        => gmdate( 'Y-m-d\TH:i:s', strtotime( $plugin['last_updated'] ) ),
			'humanized_updated'   => sprintf(
				/* translators: %s: Human-readable time difference. */
				__( '%s ago' ),
				human_time_diff( strtotime( $plugin['last_updated'] ) )
			),
		);

		$this->add_additional_fields_to_object( $block, $request );

		$response = new WP_REST_Response( $block );
		$response->add_links( $this->prepare_links( $plugin ) );

		return $response;
	}


Top ↑

Changelog

Changelog
VersionDescription
5.9.0Renamed $plugin to $item to match parent class for PHP 8 named parameter support.
5.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.