Make WordPress Core


Ignore:
Timestamp:
10/15/2025 05:12:32 PM (2 months ago)
Author:
westonruter
Message:

General: Introduce output buffering for template enhancements.

This introduces an output buffer for the entire template rendering process. This allows for post-processing of the complete HTML output via filtering before it is sent to the browser. This is primarily intended for performance optimizations and other progressive enhancements. Extenders must not rely on output buffer processing for critical content and functionality since a site may opt out of output buffering for the sake of streaming. Extenders are heavily encouraged to use the HTML API as opposed to using regular expressions in output buffer filters.

  • A new wp_before_include_template action is introduced, which fires immediately before the template file is included. This is useful on its own, as it avoids the need to misuse template_include filter to run logic right before the template is loaded (e.g. sending a Server-Timing header).
  • The wp_start_template_enhancement_output_buffer() function is hooked to this new action. It starts an output buffer, but only if there are wp_template_enhancement_output_buffer filters present, or else if there is an explicit opt-in via the wp_should_output_buffer_template_for_enhancement filter.
  • The wp_finalize_template_enhancement_output_buffer() function serves as the output buffer callback. It applies wp_template_enhancement_output_buffer filters to the buffered content if the response is identified as HTML.
  • The output buffer callback passes through (without filtering) any content for non-HTML responses, identified by the Content-Type response header.
  • This provides a standardized way for plugins (and core) to perform optimizations, such as removing unused CSS, without each opening their own ad hoc output buffer.

Developed in https://github.com/WordPress/wordpress-develop/pull/8412.

Props westonruter, nextendweb, dmsnell, flixos90, jorbin, peterwilsoncc, swissspidy, DrewAPicture, DaanvandenBergh, OptimizingMatters, tabrisrp, jonoaldersonwp, SergeyBiryukov.
Fixes #43258.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/template-loader.php

    r60791 r60936  
    114114    $template = apply_filters( 'template_include', $template );
    115115    if ( $template ) {
     116        /**
     117         * Fires immediately before including the template.
     118         *
     119         * @since 6.9.0
     120         *
     121         * @param string $template The path of the template about to be included.
     122         */
     123        do_action( 'wp_before_include_template', $template );
     124
    116125        include $template;
    117126    } elseif ( current_user_can( 'switch_themes' ) ) {
Note: See TracChangeset for help on using the changeset viewer.