Last active
August 7, 2023 13:16
-
-
Save joshuadavidnelson/4a0d6e6eda3b8d45359f6a6cbdf51a57 to your computer and use it in GitHub Desktop.
Generate a img tag for responsive images in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the feedback! I've updated the gist accordingly, also added a
apply_filters
to the output.