WP_REST_Term_Search_Handler::search_items( WP_REST_Request $request ): array

In this article

Searches terms for a given search request.

Parameters

$requestWP_REST_Requestrequired
Full REST request.

Return

array Associative array containing found IDs and total count for the matching search results.
  • ids int[]
    Found term IDs.
  • total string|int|WP_Error
    Numeric string containing the number of terms in that taxonomy, 0 if there are no results, or WP_Error if the requested taxonomy does not exist.

Source

public function search_items( WP_REST_Request $request ) {
	$taxonomies = $request[ WP_REST_Search_Controller::PROP_SUBTYPE ];
	if ( in_array( WP_REST_Search_Controller::TYPE_ANY, $taxonomies, true ) ) {
		$taxonomies = $this->subtypes;
	}

	$page     = (int) $request['page'];
	$per_page = (int) $request['per_page'];

	$query_args = array(
		'taxonomy'   => $taxonomies,
		'hide_empty' => false,
		'offset'     => ( $page - 1 ) * $per_page,
		'number'     => $per_page,
	);

	if ( ! empty( $request['search'] ) ) {
		$query_args['search'] = $request['search'];
	}

	if ( ! empty( $request['exclude'] ) ) {
		$query_args['exclude'] = $request['exclude'];
	}

	if ( ! empty( $request['include'] ) ) {
		$query_args['include'] = $request['include'];
	}

	/**
	 * Filters the query arguments for a REST API term search request.
	 *
	 * Enables adding extra arguments or setting defaults for a term search request.
	 *
	 * @since 5.6.0
	 *
	 * @param array           $query_args Key value array of query var to query value.
	 * @param WP_REST_Request $request    The request used.
	 */
	$query_args = apply_filters( 'rest_term_search_query', $query_args, $request );

	$query       = new WP_Term_Query();
	$found_terms = $query->query( $query_args );
	$found_ids   = wp_list_pluck( $found_terms, 'term_id' );

	unset( $query_args['offset'], $query_args['number'] );

	$total = wp_count_terms( $query_args );

	// wp_count_terms() can return a falsey value when the term has no children.
	if ( ! $total ) {
		$total = 0;
	}

	return array(
		self::RESULT_IDS   => $found_ids,
		self::RESULT_TOTAL => $total,
	);
}

Hooks

apply_filters( ‘rest_term_search_query’, array $query_args, WP_REST_Request $request )

Filters the query arguments for a REST API term search request.

Changelog

VersionDescription
5.6.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.