settings = $settings; } /** * Register hooks. * * @return void */ public function register() { add_filter( 'the_content', array( $this, 'optimize_content' ), 20 ); add_filter( 'post_thumbnail_html', array( $this, 'optimize_content' ), 20 ); add_filter( 'widget_text', array( $this, 'optimize_content' ), 20 ); add_filter( 'embed_oembed_html', array( $this, 'optimize_content' ), 20 ); add_filter( 'wp_get_attachment_image_attributes', array( $this, 'image_attributes' ) ); add_filter( 'acelora_site_accelerator_optimize_html', array( $this, 'optimize_content' ), 40 ); } /** * Add image attributes from WordPress image API. * * @param array $attributes Attributes. * @return array */ public function image_attributes( $attributes ) { if ( $this->settings->get( 'lazy.images', 1 ) ) { $attributes['loading'] = isset( $attributes['loading'] ) ? $attributes['loading'] : 'lazy'; $attributes['decoding'] = isset( $attributes['decoding'] ) ? $attributes['decoding'] : 'async'; } return $attributes; } /** * Optimize media markup. * * @param string $html HTML. * @return string */ public function optimize_content( $html ) { if ( '' === trim( (string) $html ) ) { return $html; } if ( $this->settings->get( 'lazy.images', 1 ) ) { $html = preg_replace_callback( '#]*>#i', array( $this, 'lazy_image' ), $html ); } if ( $this->settings->get( 'lazy.iframes', 1 ) ) { $html = preg_replace_callback( '#]*>#i', array( $this, 'lazy_iframe' ), $html ); } if ( $this->settings->get( 'lazy.videos', 1 ) ) { $html = preg_replace_callback( '#]*>#i', array( $this, 'lazy_video' ), $html ); } return $html; } /** * Add attributes to an image tag. * * @param array $matches Regex matches. * @return string */ public function lazy_image( $matches ) { $tag = $matches[0]; if ( $this->is_excluded( $tag ) ) { return $tag; } if ( false === stripos( $tag, ' loading=' ) ) { $tag = str_replace( 'is_excluded( $tag ) || false !== stripos( $tag, ' loading=' ) ) { return $tag; } return str_replace( '