WP_REST_Post_Search_Handler::prepare_item()publicWP 5.0.0

Prepares the search result for a given post ID.

Method of the class: WP_REST_Post_Search_Handler{}

No Hooks.

Return

Array. Associative array containing fields for the post based on the $fields parameter.

Usage

$WP_REST_Post_Search_Handler = new WP_REST_Post_Search_Handler();
$WP_REST_Post_Search_Handler->prepare_item( $id, $fields );
$id(int) (required)
Post ID.
$fields(array) (required)
Fields to include for the post.

Changelog

Since 5.0.0 Introduced.

WP_REST_Post_Search_Handler::prepare_item() code WP 6.7.2

public function prepare_item( $id, array $fields ) {
	$post = get_post( $id );

	$data = array();

	if ( in_array( WP_REST_Search_Controller::PROP_ID, $fields, true ) ) {
		$data[ WP_REST_Search_Controller::PROP_ID ] = (int) $post->ID;
	}

	if ( in_array( WP_REST_Search_Controller::PROP_TITLE, $fields, true ) ) {
		if ( post_type_supports( $post->post_type, 'title' ) ) {
			add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
			add_filter( 'private_title_format', array( $this, 'protected_title_format' ) );
			$data[ WP_REST_Search_Controller::PROP_TITLE ] = get_the_title( $post->ID );
			remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
			remove_filter( 'private_title_format', array( $this, 'protected_title_format' ) );
		} else {
			$data[ WP_REST_Search_Controller::PROP_TITLE ] = '';
		}
	}

	if ( in_array( WP_REST_Search_Controller::PROP_URL, $fields, true ) ) {
		$data[ WP_REST_Search_Controller::PROP_URL ] = get_permalink( $post->ID );
	}

	if ( in_array( WP_REST_Search_Controller::PROP_TYPE, $fields, true ) ) {
		$data[ WP_REST_Search_Controller::PROP_TYPE ] = $this->type;
	}

	if ( in_array( WP_REST_Search_Controller::PROP_SUBTYPE, $fields, true ) ) {
		$data[ WP_REST_Search_Controller::PROP_SUBTYPE ] = $post->post_type;
	}

	return $data;
}