wp_make_content_images_responsive

Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.

Description

(string) wp_make_content_images_responsive( (string) $content ); 

Returns (string)

Converted content with 'srcset' and 'sizes' attributes added to images.

Parameters (1)

0. $content (string)
The raw post content to be filtered.

Usage

  1. if ( !function_exists( 'wp_make_content_images_responsive' ) ) { 
  2. require_once ABSPATH . WPINC . '/media.php'; 
  3.  
  4. // The raw post content to be filtered. 
  5. $content = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wp_make_content_images_responsive($content); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/media.php  
  1. function wp_make_content_images_responsive( $content ) { 
  2. if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) { 
  3. return $content; 
  4.  
  5. $selected_images = $attachment_ids = array(); 
  6.  
  7. foreach( $matches[0] as $image ) { 
  8. if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) && 
  9. ( $attachment_id = absint( $class_id[1] ) ) ) { 
  10.  
  11. /** 
  12. * If exactly the same image tag is used more than once, overwrite it. 
  13. * All identical tags will be replaced later with 'str_replace()'. 
  14. */ 
  15. $selected_images[ $image ] = $attachment_id; 
  16. // Overwrite the ID when the same image is included more than once. 
  17. $attachment_ids[ $attachment_id ] = true; 
  18.  
  19. if ( count( $attachment_ids ) > 1 ) { 
  20. /** 
  21. * Warm object cache for use with 'get_post_meta()'. 
  22. * To avoid making a database call for each image, a single query 
  23. * warms the object cache with the meta information for all images. 
  24. */ 
  25. update_meta_cache( 'post', array_keys( $attachment_ids ) ); 
  26.  
  27. foreach ( $selected_images as $image => $attachment_id ) { 
  28. $image_meta = wp_get_attachment_metadata( $attachment_id ); 
  29. $content = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content ); 
  30.  
  31. return $content;