Skip to content

Instantly share code, notes, and snippets.

@joshuadavidnelson
Last active August 7, 2023 13:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshuadavidnelson/4a0d6e6eda3b8d45359f6a6cbdf51a57 to your computer and use it in GitHub Desktop.
Save joshuadavidnelson/4a0d6e6eda3b8d45359f6a6cbdf51a57 to your computer and use it in GitHub Desktop.
Generate a img tag for responsive images in WordPress
<?php
/**
* Get the responsive image.
*
* @param string $image_id
* @param string $image_size optional
*
* @return string $output
*/
function get_responsive_image( $image_id, $size = 'medium' ) {
// Check the image id
if( ! absint( $image_id ) ) {
return false;
}
// Check the attachment exists
$img_src = wp_get_attachment_image_url( $image_id, $size );
if ( ! $img_src ) {
return false;
}
// Gather the required elements
$img_srcset = wp_get_attachment_image_srcset( $image_id, $size );
$img_sizes = wp_get_attachment_image_sizes( $image_id, $size );
$image_alt = get_post_meta( $image_id, '_wp_attachment_image_alt', true );
$image_alt = empty( $image_alt ) ? '' : ' alt="' . esc_attr( $image_alt ) .'"';
// Build the output.
$output = '<img src="' . esc_url( $img_src ) . '"
srcset="' . esc_attr( $img_srcset ) . '"
sizes="' . esc_attr( $img_sizes ) . '"' . $image_alt . '>';
/**
* Filter the responsive image output.
*
* @param string $output the responsive image html.
* @param int $image_id the assoicated image id.
* @param mixed $size the image size, string or array.
* @return string $output
*/
return apply_filters( 'get_responsive_image', $output, $image_id, $size );
}
@frzsombor
Copy link

frzsombor commented Aug 2, 2023

Typo notice: "get_respsonsive_image"
Anyway, thanks for sharing :)

Edit: Also, I think you can replace the current $image = wp_get_attachment_image_src() "exists" check with $img_src = wp_get_attachment_image_url() (the first line in gathering elements) to save one unnecessary function call.

@joshuadavidnelson
Copy link
Author

Thanks for the feedback! I've updated the gist accordingly, also added a apply_filters to the output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment