callback = $callback; $this->level = ob_get_level() + 1; } public static function start( $callback ) { if ( ! is_callable( $callback ) ) { return false; } $buffer = new self( $callback ); if ( ! ob_start( array( $buffer, 'process' ) ) ) { return false; } self::$buffers[ $buffer->level ] = $buffer; if ( ! self::$registered ) { self::$registered = true; // Core wp_ob_end_flush_all normally runs at priority 1. add_action( 'shutdown', array( __CLASS__, 'finish' ), 0 ); } return true; } public function process( $html, $phase ) { if ( $phase & PHP_OUTPUT_HANDLER_FINAL ) { unset( self::$buffers[ $this->level ] ); } // Discarded content must never be saved as a cache entry. if ( $phase & PHP_OUTPUT_HANDLER_CLEAN ) { return $html; } return call_user_func( $this->callback, $html ); } public static function finish() { while ( isset( self::$buffers[ ob_get_level() ] ) ) { $status = ob_get_status(); if ( empty( $status['name'] ) || __CLASS__ . '::process' !== $status['name'] || empty( $status['flags'] ) || ! ( $status['flags'] & PHP_OUTPUT_HANDLER_REMOVABLE ) ) { break; } // The FINAL callback removes this exact registration, including when // WordPress or another component already closed it before shutdown. if ( ! ob_end_flush() ) { break; } } // An unrelated top buffer belongs to its owner/core, never pop it here. } }