Make WordPress Core


Ignore:
Timestamp:
07/11/2023 01:56:55 PM (12 months ago)
Author:
joemcgill
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/shortcodes.php

    r56194 r56214  
    222222    }
    223223
     224    // Ensure this context is only added once if shortcodes are nested.
     225    $has_filter = has_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
     226    $filter_added = false;
     227
     228    if ( ! $has_filter ) {
     229        $filter_added = add_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
     230    }
     231
    224232    $content = do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames );
    225233
     
    230238    $content = unescape_invalid_shortcodes( $content );
    231239
     240    // Only remove the filter if it was added in this scope.
     241    if ( $filter_added ) {
     242        remove_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
     243    }
     244
    232245    return $content;
     246}
     247
     248/**
     249 * Filter the `wp_get_attachment_image_context` hook during shortcode rendering.
     250 *
     251 * When wp_get_attachment_image() is called during shortcode rendering, we need to make clear
     252 * that the context is a shortcode and not part of the theme's template rendering logic.
     253 *
     254 * @since 6.3.0
     255 * @access private
     256 *
     257 * @return string The filtered context value for wp_get_attachment_images when doing shortcodes.
     258 */
     259function _filter_do_shortcode_context() {
     260    return 'do_shortcode';
    233261}
    234262
Note: See TracChangeset for help on using the changeset viewer.