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.