WP_REST_Posts_Controller::prepare_items_query()protectedWP 4.7.0

Determines the allowed query_vars for a get_items() response and prepares them for WP_Query.

Method of the class: WP_REST_Posts_Controller{}

Hooks from the method

Return

Array. Items query arguments.

Usage

// protected - for code of main (parent) or child class
$result = $this->prepare_items_query( $prepared_args, $request );
$prepared_args(array)
Prepared WP_Query arguments.
Default: empty array
$request(WP_REST_Request)
Full details about the request.
Default: null

Changelog

Since 4.7.0 Introduced.

WP_REST_Posts_Controller::prepare_items_query() code WP 6.5.2

protected function prepare_items_query( $prepared_args = array(), $request = null ) {
	$query_args = array();

	foreach ( $prepared_args as $key => $value ) {
		/**
		 * Filters the query_vars used in get_items() for the constructed query.
		 *
		 * The dynamic portion of the hook name, `$key`, refers to the query_var key.
		 *
		 * @since 4.7.0
		 *
		 * @param string $value The query_var value.
		 */
		$query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
	}

	if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) {
		$query_args['ignore_sticky_posts'] = true;
	}

	// Map to proper WP_Query orderby param.
	if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) {
		$orderby_mappings = array(
			'id'            => 'ID',
			'include'       => 'post__in',
			'slug'          => 'post_name',
			'include_slugs' => 'post_name__in',
		);

		if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
			$query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
		}
	}

	return $query_args;
}