Make WordPress Core


Ignore:
Timestamp:
03/02/2025 10:05:08 PM (3 months ago)
Author:
TimothyBlynJacobs
Message:

REST API: Improve performance for HEAD requests.

By default, the REST API responds to HEAD rqeuests by calling the GET handler and omitting the body from the response. While convenient, this ends up performing needless work that slows down the API response time.

This commit adjusts the Core controllers to specifically handle HEAD requests by not preparing the response body.

Fixes #56481.
Props antonvlasenko, janusdev, ironprogrammer, swissspidy, spacedmonkey, mukesh27, mamaduka, timothyblynjacobs.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php

    r59458 r59899  
    313313        }
    314314
     315        $is_head_request = $request->is_method( 'HEAD' );
     316        if ( $is_head_request ) {
     317            // Force the 'fields' argument. For HEAD requests, only term IDs are required.
     318            $prepared_args['fields'] = 'ids';
     319            // Disable priming term meta for HEAD requests to improve performance.
     320            $prepared_args['update_term_meta_cache'] = false;
     321        }
     322
    315323        /**
    316324         * Filters get_terms() arguments when querying terms via the REST API.
     
    355363        }
    356364
    357         $response = array();
    358 
    359         foreach ( $query_result as $term ) {
    360             $data       = $this->prepare_item_for_response( $term, $request );
    361             $response[] = $this->prepare_response_for_collection( $data );
    362         }
    363 
    364         $response = rest_ensure_response( $response );
     365        if ( ! $is_head_request ) {
     366            $response = array();
     367            foreach ( $query_result as $term ) {
     368                $data       = $this->prepare_item_for_response( $term, $request );
     369                $response[] = $this->prepare_response_for_collection( $data );
     370            }
     371        }
     372
     373        $response = $is_head_request ? new WP_REST_Response() : rest_ensure_response( $response );
    365374
    366375        // Store pagination values for headers.
     
    887896     */
    888897    public function prepare_item_for_response( $item, $request ) {
     898
     899        // Don't prepare the response body for HEAD requests.
     900        if ( $request->is_method( 'HEAD' ) ) {
     901            /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
     902            return apply_filters( "rest_prepare_{$this->taxonomy}", new WP_REST_Response(), $item, $request );
     903        }
    889904
    890905        $fields = $this->get_fields_for_response( $request );
Note: See TracChangeset for help on using the changeset viewer.