<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[56214] trunk: Media: Optimize images created in shortcodes.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { white-space: pre-line; overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="https://core.trac.wordpress.org/changeset/56214">56214</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"https://core.trac.wordpress.org/changeset/56214","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>joemcgill</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2023-07-11 13:56:55 +0000 (Tue, 11 Jul 2023)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>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 <a href="https://core.trac.wordpress.org/changeset/56037">[56037]</a>.

Props spacedmonkey, flixos90, thekt12, swissspidy, joemcgill.
Fixes <a href="https://core.trac.wordpress.org/ticket/58681">#58681</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpincludesmediaphp">trunk/src/wp-includes/media.php</a></li>
<li><a href="#trunksrcwpincludesshortcodesphp">trunk/src/wp-includes/shortcodes.php</a></li>
<li><a href="#trunktestsphpunittestsmediaphp">trunk/tests/phpunit/tests/media.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpincludesmediaphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/media.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/media.php   2023-07-11 13:54:42 UTC (rev 56213)
+++ trunk/src/wp-includes/media.php     2023-07-11 13:56:55 UTC (rev 56214)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -5725,9 +5725,10 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /*
</span><span class="cx" style="display: block; padding: 0 10px">         * The first elements in 'the_content' or 'the_post_thumbnail' should not be lazy-loaded,
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-         * as they are likely above the fold.
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+  * 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.
</ins><span class="cx" style="display: block; padding: 0 10px">          */
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        if ( 'the_content' === $context || 'the_post_thumbnail' === $context ) {
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ if ( 'the_content' === $context || 'the_post_thumbnail' === $context || 'do_shortcode' === $context ) {
</ins><span class="cx" style="display: block; padding: 0 10px">                 // Only elements within the main query loop have special handling.
</span><span class="cx" style="display: block; padding: 0 10px">                if ( is_admin() || ! in_the_loop() || ! is_main_query() ) {
</span><span class="cx" style="display: block; padding: 0 10px">                        $loading_attrs['loading'] = 'lazy';
</span></span></pre></div>
<a id="trunksrcwpincludesshortcodesphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/shortcodes.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/shortcodes.php      2023-07-11 13:54:42 UTC (rev 56213)
+++ trunk/src/wp-includes/shortcodes.php        2023-07-11 13:56:55 UTC (rev 56214)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -221,6 +221,14 @@
</span><span class="cx" style="display: block; padding: 0 10px">                return $content;
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        // 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' );
+       }
+
</ins><span class="cx" style="display: block; padding: 0 10px">         $content = do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        $pattern = get_shortcode_regex( $tagnames );
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -229,10 +237,30 @@
</span><span class="cx" style="display: block; padding: 0 10px">        // Always restore square braces so we don't break things like <!--[if IE ]>.
</span><span class="cx" style="display: block; padding: 0 10px">        $content = unescape_invalid_shortcodes( $content );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        // Only remove the filter if it was added in this scope.
+       if ( $filter_added ) {
+               remove_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
+       }
+
</ins><span class="cx" style="display: block; padding: 0 10px">         return $content;
</span><span class="cx" style="display: block; padding: 0 10px"> }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px"> /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ * Filter the `wp_get_attachment_image_context` hook during shortcode rendering.
+ *
+ * When wp_get_attachment_image() is called during shortcode rendering, we need to make clear
+ * that the context is a shortcode and not part of the theme's template rendering logic.
+ *
+ * @since 6.3.0
+ * @access private
+ *
+ * @return string The filtered context value for wp_get_attachment_images when doing shortcodes.
+ */
+function _filter_do_shortcode_context() {
+       return 'do_shortcode';
+}
+
+/**
</ins><span class="cx" style="display: block; padding: 0 10px">  * Retrieves the shortcode regular expression for searching.
</span><span class="cx" style="display: block; padding: 0 10px">  *
</span><span class="cx" style="display: block; padding: 0 10px">  * The regular expression combines the shortcode tags in the regular expression
</span></span></pre></div>
<a id="trunktestsphpunittestsmediaphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/media.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/media.php       2023-07-11 13:54:42 UTC (rev 56213)
+++ trunk/tests/phpunit/tests/media.php 2023-07-11 13:56:55 UTC (rev 56214)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -78,8 +78,8 @@
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><span class="cx" style="display: block; padding: 0 10px">         * Ensures that the static content media count, fetchpriority element flag and related filter are reset between tests.
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        public function set_up() {
-               parent::set_up();
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ public function tear_down() {
+               parent::tear_down();
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $this->reset_content_media_count();
</span><span class="cx" style="display: block; padding: 0 10px">                $this->reset_omit_loading_attr_filter();
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -5006,6 +5006,122 @@
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * @ticket 58681
+        *
+        * @dataProvider data_wp_get_loading_optimization_attributes_in_shortcodes
+        */
+       public function test_wp_get_loading_optimization_attributes_in_shortcodes( $setup, $expected, $message ) {
+               $attr = $this->get_width_height_for_high_priority();
+               $setup();
+
+               // The first image processed in a shortcode should have fetchpriority set to high.
+               $this->assertSame(
+                       $expected,
+                       wp_get_loading_optimization_attributes( 'img', $attr, 'do_shortcode' ),
+                       $message
+               );
+       }
+
+       public function data_wp_get_loading_optimization_attributes_in_shortcodes() {
+               return array(
+                       'main_shortcode_image_should_have_fetchpriority_high'  => array(
+                               'setup'    => function () {
+                                       global $wp_query;
+
+                                       // Set WP_Query to be in the loop and the main query.
+                                       $wp_query->in_the_loop = true;
+                                       $this->set_main_query( $wp_query );
+                               },
+                               'expected' => array(
+                                       'fetchpriority' => 'high',
+                               ),
+                               'message'  => 'Fetch priority not applied to during shortcode rendering.',
+                       ),
+                       'main_shortcode_image_after_threshold_is_loading_lazy' => array(
+                               'setup'    => function () {
+                                       global $wp_query;
+
+                                       // Set WP_Query to be in the loop and the main query.
+                                       $wp_query->in_the_loop = true;
+                                       $this->set_main_query( $wp_query );
+
+                                       // Set internal flags so lazy should be applied.
+                                       wp_high_priority_element_flag( false );
+                                       wp_increase_content_media_count( 3 );
+                               },
+                               'expected' => array(
+                                       'loading' => 'lazy',
+                               ),
+                               'message'  => 'Lazy-loading not applied to during shortcode rendering.',
+                       ),
+                       'shortcode_image_outside_of_the_loop_are_loaded_lazy'  => array(
+                               'setup'    => function () {
+                                       // Avoid setting up the WP_Query object for the loop.
+                                       return;
+                               },
+                               'expected' => array(
+                                       'loading' => 'lazy',
+                               ),
+                               'message'  => 'Lazy-loading not applied to shortcodes outside the loop.',
+                       ),
+               );
+       }
+
+       /**
+        * @ticket 58681
+        */
+       public function test_content_rendering_with_shortcodes() {
+               // The gallery shortcode will dynamically create image markup that should be optimized.
+               $content = "[gallery ids='" . self::$large_id . "' size='large']";
+               $actual  = apply_filters( 'the_content', $content );
+
+               $this->assertStringContainsString(
+                       // Since the main query and loop isn't set, this should be lazily loaded.
+                       'loading="lazy"',
+                       $actual,
+                       'Could not confirm shortcodes get optimizations applied.'
+               );
+       }
+
+       /**
+        * @ticket 58681
+        */
+       public function test_content_rendering_with_shortcodes_nested() {
+               global $wp_query;
+
+               // Set WP_Query to be in the loop and the main query.
+               $wp_query->in_the_loop = true;
+               $this->set_main_query( $wp_query );
+
+               add_shortcode(
+                       'div',
+                       function ( $atts, $content = null ) {
+                               $parsed_atts = shortcode_atts(
+                                       array(
+                                               'class' => '',
+                                       ),
+                                       $atts
+                               );
+
+                               $class = ! empty( $parsed_atts['class'] ) ? sprintf( ' class="%s"', $parsed_atts['class'] ) : null;
+
+                               return sprintf( '<div %s>%s</div>', $class, do_shortcode( $content ) );
+                       }
+               );
+
+               // The gallery shortcode will dynamically create image markup that should be optimized.
+               $content = "[div][gallery ids='" . self::$large_id . "' size='large'][div]";
+               $actual  = apply_filters( 'the_content', $content );
+
+               $this->assertStringContainsString(
+                       // Since this is in the loop, it should have a high fetchpriority.
+                       'fetchpriority="high"',
+                       $actual,
+                       'Could not confirm shortcodes get optimizations applied.'
+               );
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * @ticket 58235
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @covers ::wp_maybe_add_fetchpriority_high_attr
</span></span></pre>
</div>
</div>

</body>
</html>