Skip to content

Instantly share code, notes, and snippets.

@m-e-h
Created July 21, 2021 13:29
Show Gist options
  • Save m-e-h/cac3f62029eed906857f9b82cc2cc266 to your computer and use it in GitHub Desktop.
Save m-e-h/cac3f62029eed906857f9b82cc2cc266 to your computer and use it in GitHub Desktop.
Adds a webp image to the srcset if available in the media-library.
<?php
/**
* Adds a webp image to the srcset if available in the media-library.
*
* @param string $post_id
* @param array $args
* @return string — Image markup.
*/
function abe_get_picture_source( $post_id = 0, $args = [] ): string {
$post_id = $post_id ?: get_the_ID();
$defaults = [
'size' => 'thumbnail',
'class' => 'src-img',
'thumb_url' => get_the_post_thumbnail_url( $post_id ),
'thumb_id' => get_post_thumbnail_id( $post_id ),
'decor' => false,
];
$args = wp_parse_args( $args, $defaults );
$thumb_url = $args['thumb_url'];
$thumb_base_url = rtrim( $args['thumb_url'], 'jpengifco' );
$webp_url = "{$thumb_base_url}webp";
$thumb_src = wp_get_attachment_image_src( $args['thumb_id'], $args['size'] );
$upload_dir = wp_upload_dir();
$replace = [
home_url( $upload_dir['baseurl'] ),
$upload_dir['baseurl'],
];
$image_abs = str_replace( $replace, '', $webp_url );
$image_alt = get_the_title( $post_id );
$image_class = $args['class'];
$image_width = $thumb_src['1'] ?: '900';
$image_height = $thumb_src['2'] ?: '900';
$image_decor = $args['decor'] ? ' aria-hidden="true"' : '';
$img_src = '';
if ( file_exists( trailingslashit( $upload_dir['basedir'] ) . $image_abs ) ) {
$img_src .= "<source srcset='{$webp_url}' alt='{$image_alt}' class='picture-image webp-image {$image_class}' width='{$image_width}' height='{$image_height}' type='image/webp'>";
}
$img_src .= "<img src='{$thumb_url}' alt='{$image_alt}' class='picture-image {$image_class}' width='{$image_width}' height='{$image_height}'$image_decor>";
return $img_src;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment