Disable lazy loading for specific image

It is a bit hard to remove lazy load for specific images. We need to do some some hacky DOM magic to get this done.

/**
 * Image
 */
class Image {
	/**
	 * Construct
	 */
	public function __construct() {
		add_filter( 'the_content', array( $this, 'disable_lazy_loading' ) );
	}

	/**
	 * Disable lazy loading if specific class is present.
	 */
	public function disable_lazy_loading( $content ) {
		if ( empty( $content ) ) {
			return $content;
		}

		$content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );

		$document = new DOMDocument();

		libxml_use_internal_errors( true );

		$document->loadHTML( utf8_decode( $content ) );

		libxml_clear_errors();

		$figures = $document->getElementsByTagName( 'figure' );

		if ( 0 === $figures->length ) {
			return $content;
		}

		foreach ( $figures as $figure ) {
			$figure_classes = $figure->getAttribute( 'class' );
			$figure_classes = explode( ' ', $figure_classes );

			if ( in_array( 'no-lazy-loading', $figure_classes ) ) {
				$image = $figure->getElementsByTagName( 'img' )[0];
	
				$image->removeAttribute( 'loading' );
			}
		}

		// Hack: Remove unneeded tags.
		$document->removeChild( $document->doctype );

		$html = str_replace(
			array(
				'<html>',
				'</html>',
				'<body>',
				'</body>',
			),
			'',
			$document->saveHTML()
		);

		// Return.
		return $html;
	}
}