To replace <img>
tags with <picture>
tags in the content of your posts, follow these steps:
Add a filter for post content:
This filter will modify the post content to replace <img>
tags with <picture>
tags, allowing for responsive images based on screen size and resolution.
Implement the replacement function:
The function replace_content_images_with_picture_tags
will find all tags in the post content and replace them with tags.
// Add a filter to modify the content of posts and replace img tags with picture tags
add_filter( 'the_content', 'replace_content_images_with_picture_tags' );
/**
* Replace img tags with picture tags in post content
*
* @param string $content The post content.
* @return string Modified post content with picture tags.
*/
function replace_content_images_with_picture_tags( $content ) {
if ( preg_match_all( '/<img[^>]+>/i', $content, $matches ) ) {
foreach ( $matches[0] as $img_tag ) {
if ( preg_match( '/wp-image-(\d+)/i', $img_tag, $class_id ) ) {
$attachment_id = $class_id[1];
$img_url = wp_get_attachment_image_url( $attachment_id, 'full' );
$img_srcset = wp_get_attachment_image_srcset( $attachment_id, 'full' );
$img_sizes = wp_get_attachment_image_sizes( $attachment_id, 'full' );
$picture_tag = '<picture>';
$picture_tag .= '<source srcset="' . esc_attr( $img_srcset ) . '" sizes="' . esc_attr( $img_sizes ) . '" media="(min-width: 768px)">';
$picture_tag .= str_replace( '<img', '<img src="' . esc_url( $img_url ) . '"', $img_tag );
$picture_tag .= '</picture>';
$content = str_replace( $img_tag, $picture_tag, $content );
}
}
}
return $content;
}