A WordPress-centric search engine for devs and theme authors



wp_filter_content_tags ›

Since5.5.0
Deprecatedn/a
wp_filter_content_tags ( $content, $context = null )
Parameters: (2)
  • (string) $content The HTML content to be filtered.
    Required: Yes
  • (string) $context Optional. Additional context to pass to the filters. Defaults to `current_filter()` when not set.
    Required: No
    Default: null
See:
Returns:
  • (string) Converted content with images modified.
Defined at:
Codex:

Filters specific tags in post content and modifies their markup.

This function adds srcset, sizes, and loading attributes to img HTML tags.


Source

function wp_filter_content_tags( $content, $context = null ) {
	if ( null === $context ) {
		$context = current_filter();
	}

	$add_loading_attr = wp_lazy_loading_enabled( 'img', $context );

	if ( false === strpos( $content, '<img' ) ) {
		return $content;
	}

	if ( ! preg_match_all( '/<img\s[^>]+>/', $content, $matches ) ) {
		return $content;
	}

	// List of the unique `img` tags found in $content.
	$images = array();

	foreach ( $matches[0] as $image ) {
		if ( preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) ) {
			$attachment_id = absint( $class_id[1] );

			if ( $attachment_id ) {
				// If exactly the same image tag is used more than once, overwrite it.
				// All identical tags will be replaced later with 'str_replace()'.
				$images[ $image ] = $attachment_id;
				continue;
			}
		}

		$images[ $image ] = 0;
	}

	// Reduce the array to unique attachment IDs.
	$attachment_ids = array_unique( array_filter( array_values( $images ) ) );

	if ( count( $attachment_ids ) > 1 ) {
		/*
		 * Warm the object cache with post and meta information for all found
		 * images to avoid making individual database calls.
		 */
		_prime_post_caches( $attachment_ids, false, true );
	}

	foreach ( $images as $image => $attachment_id ) {
		$filtered_image = $image;

		// Add 'srcset' and 'sizes' attributes if applicable.
		if ( $attachment_id > 0 && false === strpos( $filtered_image, ' srcset=' ) ) {
			$filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id );
		}

		// Add 'loading' attribute if applicable.
		if ( $add_loading_attr && false === strpos( $filtered_image, ' loading=' ) ) {
			$filtered_image = wp_img_tag_add_loading_attr( $filtered_image, $context );
		}

		if ( $filtered_image !== $image ) {
			$content = str_replace( $image, $filtered_image, $content );
		}
	}

	return $content;
}