[wp-trac] [WordPress Trac] #55510: The `wp_content_img_tag` filter can appear to run twice when used to wrap image tags

WordPress Trac noreply at wordpress.org
Mon Apr 11 23:41:55 UTC 2022

#55510: The `wp_content_img_tag` filter can appear to run twice when used to wrap
image tags
 Reporter:  peterwilsoncc                 |       Owner:  flixos90
     Type:  defect (bug)                  |      Status:  assigned
 Priority:  normal                        |   Milestone:  6.0
Component:  Media                         |     Version:
 Severity:  normal                        |  Resolution:
 Keywords:  needs-patch needs-unit-tests  |     Focuses:

Comment (by flixos90):

 @peterwilsoncc @pbearne The problem indeed occurs when the exact same
 image tag is included in the content multiple times.

 This has not been a problem for WordPress core itself, since it will
 adjust the "duplicate" image tag in the same way. The following
 `str_replace()` (which by definition replaces all occurrences in the
 content) will technically not do anything since the unmodified image tag
 has already been replaced throughout the content before.

 When wrapping an image tag without further modifying it though, it means
 that even after the replacement the original image tag remains in the
 content, hence the duplicate filter run replaces it again (which in case
 of a filter that wants to wrap the image with `<span><img /></span>` will
 get `<span><span><img /></span></span>`.

 So while this is now a bug, it technically has always been a somewhat
 wasteful implementation, re-running the logic unnecessarily for duplicate
 instances of the same image tag. Fortunately there's an easy fix for it:
 We can simply unset the respective lookup key in the `$images` variable
 within `wp_filter_content_tags()` to not process the same tag again.

 Note that we should make the same fix for iframes. They don't have a
 filter so this is technically not a bug there, but still just as wasteful.

Ticket URL: <https://core.trac.wordpress.org/ticket/55510#comment:3>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform

More information about the wp-trac mailing list