Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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_respsonsive_image( $image_id, $size = 'medium' ) {
// Check the image id
if( ! $image_id = absint( $image_id ) )
return false;
// Check the attachment exists
if( ! $image = wp_get_attachment_image_src( $image_id, $size ) ) {
return false;
}
// Gather the required elements
$img_src = wp_get_attachment_image_url( $image_id, $size );
$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 ) .'"';
// Return the built output
return '<img src="' . esc_url( $img_src ) . '"
srcset="' . esc_attr( $img_srcset ) . '"
sizes="' . esc_attr( $img_sizes ) . '"' . $image_alt . '>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.