load_assets_on_demand() ||
FALSE == $this->move_css_to_head() ) {
return;
}
add_action( 'template_redirect', array( $this, 'buffer_start' ), 1 );
add_filter( 'getwid/html/output', array( $this, 'filter_css' ) );
add_filter( 'getwid/html/output', array( $this, 'filter_test' ) );
// Filter Autoptimize plugin output
add_filter( 'autoptimize_filter_html_before_minify', array( $this, 'filter_css' ) );
}
/**
* Setup output buffering if needed.
*
* @return void
*/
public function buffer_start() {
if ( $this->should_buffer() ) {
ob_start( array( $this, 'buffer_end' ) );
}
}
/**
* Processes/optimizes the output-buffered content and returns it.
* If the content is not processable, it is returned unmodified.
*
* @param string $html Buffered content.
*
* @return string
*/
public function buffer_end( $html ) {
// Bail early without modifying anything if we can't handle the content.
if ( ! $this->is_valid_buffer( $html ) ) {
return $html;
}
// Apply any filters to the final output
$html = apply_filters( 'getwid/html/output', $html );
return $html;
}
/*
* Test replacement
*
* @param string $html Buffered content.
*
* @return string
*/
public function filter_test( $html ) {
if ( $this->alreadyoptimized ) {
$html .= PHP_EOL . '';
}
return $html;
}
/*
* Find stylesheets of our blocks in original HTML and move them to Header
*
* @param string $html Buffered content.
*
* @return string
*
* Source \plugins\autoptimize\classes\autoptimizeStyles.php
*/
public function filter_css( $html ) {
if ( $this->alreadyoptimized ) {
return $html;
}
$css = array();
$blocks = getwid()->blocksManager()->getBlocks();
//var_dump($blocks);exit;
$optimize_more = apply_filters( 'getwid/optimize/assets', [] );
/*
* Blocks array example:
* ["getwid/anchor"] => object(Getwid\Blocks\Anchor) {}
*
* Style tag example:
*
*/
// Find stylesheets in original html
if ( preg_match_all( '#(]*stylesheet[^>]*>)#Usmi', $html, $tag_matches ) ) {
foreach ( $tag_matches[0] as $tag ) {
if ( preg_match( '#', $html );
}
}
}
}
// Process stylesheets if we found ones
if ( ! empty( $css ) ) {
// move stylesheet to a new positon
$replace_tag = array( '', 'after' );
// Debug
$css_scope = PHP_EOL . '' . PHP_EOL . "\t";
// Print stylesheets
$css_scope .= implode( PHP_EOL . "\t", $css );
// Debug
$css_scope .= PHP_EOL . '' . PHP_EOL;
//var_dump($css_scope);exit;
$html = $this->inject_in_html( $css_scope, $replace_tag, $html );
// Mark as optimized
$this->alreadyoptimized = true;
}
return $html;
}
/**
* Injects/replaces the given payload markup into `$html`
* at the specified location.
* If the specified tag cannot be found, the payload is appended into
* $html along with a warning wrapped inside tags.
*
* @param string $payload Markup to inject.
* @param array $where Array specifying the tag name and method of injection.
* Index 0 is the tag name (i.e., `