From 725f39d73fbf0ace938f7bf92ee6556009ae2771 Mon Sep 17 00:00:00 2001 From: Joe McGill Date: Tue, 11 Jul 2023 13:58:21 +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. Built from https://develop.svn.wordpress.org/trunk@56214 git-svn-id: http://core.svn.wordpress.org/trunk@55726 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- wp-includes/media.php | 5 +++-- wp-includes/shortcodes.php | 28 ++++++++++++++++++++++++++++ wp-includes/version.php | 2 +- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/wp-includes/media.php b/wp-includes/media.php index 1dc610f550..b706cd9897 100644 --- a/wp-includes/media.php +++ b/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/wp-includes/shortcodes.php b/wp-includes/shortcodes.php index ea55f3373a..4d23521f44 100644 --- a/wp-includes/shortcodes.php +++ b/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