Imagify / Image Optimization for theme inline div background?


I’m using the imgaify plugin to serve webp images. Using their plugin a normal tag ends up looking like this:

<picture class="attachment-large size-large wp-post-image">
<source type="image/webp" srcset="https://.../image.jpg.webp 870w, https://.../image-300x128.jpg.webp 300w" sizes="(max-width: 870px) 100vw, 870px">
<img width="870" height="372" src="https://.../img.jpg" alt="Questions? We Can Help" srcset="https://.../image.jpg 870w, https://.../image-300x128.jpg 300w" sizes="(max-width: 870px) 100vw, 870px">

This works fine and well for normal img tag replacement. Here is where i am running into issue:

On some of the pages, my custom theme grabs the featured image and sets this image to the background of a DIV inline with CSS. No optimization is applied here heavily weighing down the page size.

I’m unsure what the best approach would be to fix this:

  1. Create a custom function that returns the optimized jpg/png version of the featured image and return that?

  2. Create a custom function that will spit out the webp version of the file (does one exist?) then use something like monderizr to detect webp support and display the correct styles?

I’m not currently using modernizr so adding another script may outweigh any speed gains. Is there a simpler solution?

Here is how my theme generates the code for the featured image:

<?php if ( has_post_thumbnail() ) : ?>
<div class="innerpage-banner" style="background:url(<?php $src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full', false ); echo esc_url( $src[0] ); ?>) no-repeat; background-size:cover; background-position: center center;">
<?php else: ?>
<?php endif; ?>
DDulla 2 years 2020-12-24T15:10:39-05:00 0 Answers 5 views 0

Leave an answer