Skip to content

Instantly share code, notes, and snippets.

@Niq1982
Created June 21, 2017 11:30
Show Gist options
  • Save Niq1982/47bd85a3e1bddf80ee0256f8a7d38b34 to your computer and use it in GitHub Desktop.
Save Niq1982/47bd85a3e1bddf80ee0256f8a7d38b34 to your computer and use it in GitHub Desktop.
Make images added through divi (or other shortcode-based page builder) responsive in multisite
// Make DIVI images responsive by adding srcset
function make_divi_img_responsive( $output, $tag ) {
if ( 'et_pb_image' !== $tag ) {
return $output;
}
if ( ! preg_match_all( '/<img [^>]+>/', $output, $images ) ) {
return $output;
}
foreach ( $images as $image ) {
if ( ! preg_match( '/<img(.*?)src=("|\'|)(.*?)("|\'| )(.*?)>/s', $image[0], $matches ) ) {
return $output;
}
$image_url = $matches[3];
$upload_dir = wp_get_upload_dir();
$parsed_dir = wp_parse_url( $upload_dir['baseurl'] );
$image_url = str_replace( $parsed_dir['path'] . '/', '', $image_url );
$attachment_id = attachment_url_to_postid( $image_url );
if ( 0 === $attachment_id ) {
return $output;
} else {
$image_meta = wp_get_attachment_metadata( $attachment_id );
return wp_image_add_srcset_and_sizes( $image[0], $image_meta, $attachment_id );
}
}
}
add_filter( 'do_shortcode_tag', 'make_divi_img_responsive', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment