3 Code Snippets That Will Boost Your WordPress Website | Kristiyan Katsarov

3 Code Snippets That Will Boost Your WordPress Website

By Kristiyan Katsarov
Kristiyan Katsarov
Published on July 26, 2021

I was optimizing a lot for core web vitals lately and saw some common mistakes a lot of themes and plugins do. I decided to share 3 code snippets which you can use in your theme or via plugin to improve the core web vitals score of your website.

Delay Inline JavaScript

This script should be used in a combination with any caching plugin. The functionality already exists in WP Rocket, so I adopted my script to W3 Total Cache. What this script basically does, is that it replaces the JavaScript contents in inline <script> tags so that the script is executed after the DOMContentLoaded Event.

add_filter('w3tc_process_content', function( $content ) {
	preg_match_all( "/<script(?:[^>]*)>(?<content>[\s\S]*?)<\/script>/ims", $content, $matches, PREG_SET_ORDER );
	
	foreach ( $matches as $code ) {
		if ( strpos( $code['content'], 'jQuery(' ) === false ) {
			continue;
		}
		if ( strpos( $code['content'], 'DOMContentLoaded' ) !== false ) {
			continue;
		}
		if ( empty( $code['content'] ) ) {
			continue;
		}
		if ( preg_match( '/(application\/ld\+json)/i', $code[0] ) ) {
			continue;
		}

		$new_code = "<script>document.addEventListener('DOMContentLoaded', () => { " . $code['content'] . "});</script>";
		$content = str_replace( $code[0], $new_code, $content );
	}
	return $content;
}, PHP_INT_MAX);

Often this is the part that turns the web vitals from yellow to green - optimizing the inline code, because a lot of plugins are just a mess! The code snippet is also available as a gist on GitHub - Delay Inline JavaScript With W3 Total Cache.

WebP Code Snippet - Finally!

I haven't found a snippet, just a bunch of plugins with a lot of overhead that make a WebP copy of an image. Of course they all want to sell the pro version and at the end of the day, none of the free plugins (with small exceptions) does the job correctly. Here is a link to the gist - WebP Code Snippet.

The job can be done with a simple snippet and web server adjustment, here is the code:

function generate_webp_from_file($file, $compression_quality = 80)
{
    // check if file exists
    if (!file_exists($file)) {
        return false;
    }

    // If output file already exists return path
    $output_file = $file . '.webp';
    if (file_exists($output_file)) {
        return $output_file;
    }

    $file_type = strtolower(pathinfo($file, PATHINFO_EXTENSION));
	
    if (function_exists('imagewebp')) {
        switch ($file_type) {
            case 'jpeg':
            case 'jpg':
                $image = imagecreatefromjpeg($file);
                break;

            case 'png':
                $image = imagecreatefrompng($file);
                imagepalettetotruecolor($image);
                imagealphablending($image, true);
                imagesavealpha($image, true);
                break;

            case 'gif':
                $image = imagecreatefromgif($file);
                break;
            default:
                return false;
        }

        // Save the image
        $result = imagewebp($image, $output_file, $compression_quality);
        if (false === $result) {
            return false;
        }

        // Free up memory
        imagedestroy($image);

        return $output_file;
    } elseif (class_exists('Imagick')) {
		error_log( $file_type );
		if ($file_type !== 'png') {
			return false;	
		}
		
        $image = new Imagick();
        $image->readImage($file);

        if ($file_type === 'png') {
            $image->setImageFormat('webp');
            $image->setImageCompressionQuality($compression_quality);
            $image->setOption('webp:lossless', 'true');
        }

        $image->writeImage($output_file);
        return $output_file;
    }

    return false;
}

/**
 * Generate .webp copy from each size when an attachment is uploaded
 */
add_action( 'wp_generate_attachment_metadata', 'wpse_256351_upload', 10, 3 );
function wpse_256351_upload( $meta, $id, $content ) {
  	$upload_dir = wp_get_upload_dir()['basedir'] . '/';
	$file = $upload_dir . $meta['file'];
	generate_webp_from_file( $file );
	
	foreach( $meta['sizes'] as $key => $file ) {
		$path = wp_get_upload_dir()['path'] . '/' . $file['file'];
		generate_webp_from_file( $path );
	}
	return $meta;
}

/**
 * Delete the all .webp copies
 */
add_action( 'delete_attachment', function( $id, $post ) {
	$file = get_attached_file( $id );
	$original_webp = "$file.webp";
	if( file_exists( $original_webp ) ) {
		unlink( $original_webp );
	}
	
	$meta = wp_get_attachment_metadata( $id );
	foreach( $meta['sizes'] as $key => $file ) {
		$path = wp_get_upload_dir()['path'] . '/' . $file['file'];
		$webp_file = "$path.webp";
		if( file_exists( $webp_file ) ) {
			unlink( $webp_file );
		}
	}
}, 10, 2);

What needs to be adjusted is your web server. Luckily for nginx and apache, I can provide two little snippets that work like a charm, so webp is served to every supported browser.

Apache

AddType image/webp .webp

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{HTTP_ACCEPT} image/webp
  RewriteCond %{REQUEST_FILENAME} -f
  RewriteCond %{REQUEST_FILENAME}.webp -f
  RewriteRule ^/?(.+?)\.(jpe?g|png)$ /\.$2.webp [NC,T=image/webp,E=EXISTING:1,E=ADDVARY:1,L]

  <IfModule mod_headers.c>
    <FilesMatch "(?i)\.(jpe?g|png)$">
      Header append "Vary" "Accept"
    </FilesMatch>
  </IfModule>
</IfModule>

NGINX

location ~* \.(png|jpe?g)$ {
	expires 365d;
	add_header Pragma "public";
	add_header Cache-Control "public";
	add_header Vary Accept;

	if ($http_accept !~* "webp") {
		break;
	}

	try_files $uri$webp_suffix $uri =404;
}

Optimize WooCommerce

WooCommerce is a great plugin. Unfortunately they load all types of libraries and css codes, that it basically loads a bunch of unused code (e.g. on the homepage) which only slows down the HTTP requests to your website.

I created a code snippet (still work in progress though) that removes all the unnecessary WooCommerce scripts and styles if they are loaded on a non-woocommerce page. Gist: Optimize WooCommerce For Web Vitals

/**
 * Disable WooCommerce block styles (front-end).
 */
function slug_disable_woocommerce_block_styles() {
	if( function_exists( 'is_woocommerce') ) {
		if( !is_woocommerce() && !is_cart() && !is_checkout() ) {
			wp_dequeue_style( 'wc-block-style' );	
			wp_dequeue_style( 'wp-block-library' );
			wp_dequeue_style( 'woocommerce-layout' );
			wp_dequeue_style( 'woocommerce-smallscreen' );
			wp_dequeue_style( 'woocommerce-general' );
			wp_dequeue_style( 'photoswipe' );
			wp_dequeue_style( 'photoswipe-default-skin' );
			wp_dequeue_script( 'wc-add-to-cart' );
			wp_dequeue_script( 'photoswipe' );
			wp_dequeue_script( 'photoswipe-ui-default' );
			wp_dequeue_script( 'wc-cart-fragments' );
		}
	}
}
add_action( 'wp_enqueue_scripts', 'slug_disable_woocommerce_block_styles', PHP_INT_MAX );

add_filter( 'woocommerce_enqueue_styles', function($arr) {
	if( function_exists( 'is_woocommerce') ) {
		if( !is_woocommerce() && !is_cart() && !is_checkout() ) {
			return [];
		}
	}
	return $arr;
} );

/**
 * Remove lightbox
 */
add_action( 'wp', function() {
   remove_theme_support( 'wc-product-gallery-lightbox' ); // removes photoswipe markup on frontend	
}, PHP_INT_MAX );

Beware that this script removes all WooCommerce libraries on non-woocommerce pages (e.g. shop or single product) - if you need the libraries on a specific page, you need to adjust the snippet to your needs.

That's it, I hope you like the scripts and give feedback in the gist of each one - if you need professional help with core web vitals get in touch with me 🙂