From ed174730d3c2bca27290ece3b88a8f97fa976be9 Mon Sep 17 00:00:00 2001 From: Joe McGill Date: Tue, 11 Jul 2023 13:56:55 +0000 Subject: [PATCH] Media: Optimize images created in shortcodes. This fixes an issue where images dynamically created during shortcode rendering (e.g., shortcode image galleries), were not getting image optimizations like `loading="lazy"` or `fetchpriority="hight"` applied. Note that even after this commit, shortcodes are processed after the main content images, which can affect the order in which optimizations are applied in content areas. Follow-up to [56037]. Props spacedmonkey, flixos90, thekt12, swissspidy, joemcgill. Fixes #58681. git-svn-id: https://develop.svn.wordpress.org/trunk@56214 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/media.php | 5 +- src/wp-includes/shortcodes.php | 28 ++++++++ tests/phpunit/tests/media.php | 120 ++++++++++++++++++++++++++++++++- 3 files changed, 149 insertions(+), 4 deletions(-) diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 1dc610f550..b706cd9897 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -5725,9 +5725,10 @@ function wp_get_loading_optimization_attributes( $tag_name, $attr, $context ) { /* * The first elements in 'the_content' or 'the_post_thumbnail' should not be lazy-loaded, - * as they are likely above the fold. + * as they are likely above the fold. Shortcodes are processed after content images, so if + * thresholds haven't already been met, apply the same logic to those as well. */ - if ( 'the_content' === $context || 'the_post_thumbnail' === $context ) { + if ( 'the_content' === $context || 'the_post_thumbnail' === $context || 'do_shortcode' === $context ) { // Only elements within the main query loop have special handling. if ( is_admin() || ! in_the_loop() || ! is_main_query() ) { $loading_attrs['loading'] = 'lazy'; diff --git a/src/wp-includes/shortcodes.php b/src/wp-includes/shortcodes.php index ea55f3373a..4d23521f44 100644 --- a/src/wp-includes/shortcodes.php +++ b/src/wp-includes/shortcodes.php @@ -221,6 +221,14 @@ function do_shortcode( $content, $ignore_html = false ) { return $content; } + // Ensure this context is only added once if shortcodes are nested. + $has_filter = has_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' ); + $filter_added = false; + + if ( ! $has_filter ) { + $filter_added = add_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' ); + } + $content = do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames ); $pattern = get_shortcode_regex( $tagnames ); @@ -229,9 +237,29 @@ function do_shortcode( $content, $ignore_html = false ) { // Always restore square braces so we don't break things like