Skip to content

Require WP 6.3 and use core HTML and loading APIs - #1400

Open
utkarshcloudinary wants to merge 8 commits into
developfrom
feat/wp-core-min-version-apis
Open

utkarshcloudinary wants to merge 8 commits into
developfrom
feat/wp-core-min-version-apis

Conversation

@utkarshcloudinary

@utkarshcloudinary utkarshcloudinary commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Sets WordPress 6.3 as the minimum version (readme.txt already says 6.3) and uses the core APIs that this makes available.

 cloudinary.php
+  Requires at least: 6.3 / Requires PHP: 7.4   # WP blocks activation on older sites

 Delivery::parse_element / Utils::get_tag_attributes
-  shortcode_parse_atts( trim( $tag, '</>' ) )
+  Utils::parse_html_tag()  -> WP_HTML_Tag_Processor (6.2)

 Filter::filter_out_local (front end)
-  str_replace( '/>', ' class="wp-image-N"/>' )
-  str_replace( '/>', ' loading="lazy" />' )      # saved into post content
+  add_front_end_attributes() -> set_attribute( 'class' )

 Delivery::rebuild_tag
-  wp_image_add_srcset_and_sizes( $original )     # appends a 2nd srcset
+  wp_image_add_srcset_and_sizes( remove_tag_attribute( $original, 'srcset' ) )
+  wp_img_tag_add_auto_sizes( $rebuilt )           # keeps core sizes="auto" (6.7+)

Lazy load no longer replaces images at the top of the page. It uses the same signals as core (6.3):

is_in_initial_viewport( img )
  fetchpriority="high"                 -> eager (LCP candidate)
  loading="lazy" | fetchpriority="low" -> lazy
  otherwise                            -> eager for the first wp_omit_loading_attr_threshold() images (default 3)
  apply_filters( 'cloudinary_lazy_load_in_initial_viewport', ... )

Cleanup: removes the fallbacks for WP versions below 6.3 (function_exists() guards, the get_post_parent() fallback, the class-http.php include, the pre-5.1 render_block video fallback). filter_video_block_render_block() stays for third-party callers, deprecated since 3.4.0 with _deprecated_function(). On WP below 6.3 the plugin does not load and shows an admin notice (wp_admin_notice() when available), as the header alone does not stop updates through Composer or a zip file.

Not included: the Interactivity API (needs 6.5 and a gallery/player rewrite) and wp_admin_notice() for the plugin's own notice UI (that UI has icons and timed dismiss, which core does not support).

Approach

  • Commit 1: header and removal of the old fallbacks.
  • Commit 2: HTML API parsing and tag edits. Attribute values are decoded and not unslashed. A tag cut short by a raw > in a value is now skipped, instead of being rebuilt into broken markup.
  • Commit 3: initial viewport check in Lazy_Load::bypass_lazy_load(), and sizes="auto" on rebuilt tags.
  • Commit 4: slash the replacement cache before update_post_meta(). Because the parser now keeps backslashes, a cached page rendered alt="C:\new" as alt="C:new" while the uncached page did not. A regression test covers it (fails without the fix).
  • Commit 5: the breakpoints e2e test expects core's sizes="auto" on its lazy image.
  • Commit 6: review fixes.
    • Video block src/poster are replaced through the HTML API (Video::replace_tag_urls()). The decoded values no longer matched &amp; in the raw HTML.
    • Runtime WordPress version check, as described above.
    • The replacement cache is cleared on cloudinary_version_upgrade, so sites with cached pages get the new markup after the update.
    • Lazy load bypass classes are checked before the viewport check, so bypassed images do not use up eager places.
  • Commit 7: new filter and deprecation tagged for 3.4.0.

Evidence

The same parser code, run against the WP 6.3 WP_HTML_Tag_Processor:

input:  <IMG SRC="https://e.com/a.jpg?a=1&amp;b=2" alt="a &gt; b" fetchpriority=high hidden class="x y" />
output: tag=img  src=https://e.com/a.jpg?a=1&b=2  alt="a > b"  fetchpriority=high  [hidden]  class="x y"

Class insertion on a tag without a self-closing slash:

  • Before: <img src="a.jpg"> stays unchanged (there is no /> to replace)
  • After: <img class="wp-image-12" src="a.jpg">

sizes on a rebuilt lazy image (WP 7.2 RC4):

  • Before: sizes="(max-width: 300px) 100vw, 300px" (core's auto was dropped when the tag was rebuilt)
  • After: sizes="auto, (max-width: 300px) 100vw, 300px"

New unit tests are in tests/phpunit/tests/test-wp-core-apis.php, test-delivery-parse-element.php and test-video-replace-urls.php. A new e2e case checks that the first image with no loading hint is not lazy loaded. They cover the parser, the class insertion, the srcset removal, the viewport threshold and core hints, and the new filter.

Browser check (Chrome DevTools, local wp-env, WP 7.2 RC4, lazy load on, 6 synced images, image 5 has fetchpriority="high"):

Image develop This branch
Hero (core fetchpriority="high") placeholder, lazy Cloudinary URL, eager
Images 1–2 placeholder, lazy Cloudinary URL, eager
Images 3–4 (core loading="lazy") placeholder, lazy placeholder, lazy, swaps to Cloudinary on scroll
Image 5 (fetchpriority="high") placeholder, lazy Cloudinary URL, eager
  • wp_omit_loading_attr_threshold = 1: only the hero is eager. cloudinary_lazy_load_in_initial_viewport = false: all lazy, same as develop.
  • Lazy load off with breakpoints on: develop drops core's sizes="auto" from lazy images; this branch keeps it. Each image has one srcset.
  • Video block plays from Cloudinary. Cached and uncached renders are the same. No console errors or warnings.

QA notes

  1. Turn on lazy loading. Publish a post with 5 or more images and no loading attributes. On the front end, the first 3 images (default threshold) have a Cloudinary src and no data-cloudinary="lazy". The later images have the placeholder and lazy load on scroll.
  2. Add add_filter( 'wp_omit_loading_attr_threshold', fn() => 1 );. Only the first image loads eagerly.
  3. Make sure the featured or hero image has fetchpriority="high" and is never a lazy placeholder.
  4. Add add_filter( 'cloudinary_lazy_load_in_initial_viewport', '__return_false' );. All images are lazy loaded again, as on develop.
  5. Turn off lazy loading. Lazy images keep sizes="auto, …" on WP 6.7 or higher, and each image has only one srcset.
  6. Video block with the Cloudinary player on and off: the video still renders. With the player off, a src or poster URL with a query string (?a=1&b=2) is changed to the Cloudinary URL.
  7. On a WP 6.2 site, the plugin cannot be activated, and if it is already installed, it does not load and shows an admin notice.
  8. A PDF in a File block: links and the embedded viewer are unchanged, and the preview image is still a Cloudinary JPG.

Merge Danger

Door: two-way. No data or option changes. A revert restores the old behaviour. Content saved after this change no longer contains loading="lazy", which is the core default.

Blast Radius: front end markup of every image that Delivery rewrites.

  • The first images on each page now load eagerly when lazy load is on. This is faster for LCP but uses more bytes before the page is visible. Sites can change it with wp_omit_loading_attr_threshold or cloudinary_lazy_load_in_initial_viewport.
  • Parser differences: attribute names are now lowercase and backslashes in values are kept. Code on the cloudinary_parse_element / cloudinary_pre_image_tag filters that expected the old output can see different values.
  • Sites on WP versions below 6.3 cannot activate new versions of the plugin.

readme.txt already declares WordPress 6.3 as the minimum. Add the
same "Requires at least" and "Requires PHP" headers to the plugin
file, so WordPress blocks activation on older sites.

Remove the code paths that only ran on WordPress versions below 6.3:
the function_exists() checks for wp_get_original_image_path/url,
has_block and wp_print_inline_script_tag, the get_post_parent()
fallback, the pre-5.9 class-http.php include and the pre-5.1
render_block fallback for video blocks. The fallback callback stays,
marked deprecated, for third-party callers.

Use wp_admin_notice() (WP 6.4+) for the PHP version notice when it is
available.
Replace shortcode_parse_atts() and str_replace() tag handling with
WP_HTML_Tag_Processor (WP 6.2+).

- Utils::parse_html_tag() reads the tag name and attributes with the
  HTML API. Values are decoded and not unslashed, and a ">" inside a
  value no longer cuts the tag short. Delivery::parse_element() and
  Utils::get_tag_attributes() use it.
- Filter::add_front_end_attributes() sets the missing class with
  set_attribute(), instead of inserting text before "/>", which did
  nothing on tags without a self-closing slash.
- The content filter no longer stores loading="lazy" in post content.
  The check called wp_lazy_loading_enabled with the wrong arguments,
  and a stored value stops core from finding above the fold images.
- Remove the old srcset before wp_image_add_srcset_and_sizes(), which
  appends a second srcset instead of replacing the first one.
Cloudinary lazy load replaced every image with a placeholder,
including the LCP image, which delays the largest paint.

Follow the WordPress 6.3 loading optimization decisions instead:
- An image with fetchpriority="high" is the LCP candidate and is
  never lazy loaded, so core's fetchpriority now takes effect.
- An image with loading="lazy" or fetchpriority="low" is below the
  fold and is lazy loaded.
- Other images count towards wp_omit_loading_attr_threshold (3 by
  default) in document order. The first ones load eagerly.

The new cloudinary_lazy_load_in_initial_viewport filter can change
the result per image.

Delivery rebuilds the tag after core adds sizes="auto" (WP 6.7+), so
run wp_img_tag_add_auto_sizes() on the rebuilt tag to keep it.

The breakpoints e2e fixture now marks its image loading="lazy", as it
is the only image in the post and would otherwise load eagerly.
The HTML API parser keeps backslashes in attribute values, which
shortcode_parse_atts() used to strip. update_post_meta() unslashes
the value, so the cached replacement for alt="C:\new" was saved as
alt="C:new" and a cached page rendered a different tag than an
uncached one.

Slash the replacements before they are saved, and move the write
into Delivery::update_context_cache() so it can be tested.
The breakpoints fixture image is now natively lazy loaded, and
Delivery keeps the "auto" that WordPress 6.7+ adds to the sizes of
lazy loaded images. Update the expected sizes attribute.
- Video blocks: replace the src and poster through the HTML API in
  the new Video::replace_tag_urls(). get_tag_attributes() now returns
  decoded values, so str_replace() missed URLs with "&amp;" in the
  HTML and left the local URL when the Cloudinary player is off.
- Stop loading the plugin on WordPress below 6.3 and show a notice.
  The header only blocks activation from the admin, not updates with
  Composer or a zip file.
- Clear the replacement cache on cloudinary_version_upgrade. Cached
  tags skip rebuild_tag(), so pages kept the old markup.
- Check the lazy load bypass classes before the viewport check, so
  bypassed images do not use up the eager places.
- Call _deprecated_function() in the deprecated video callback.
- Move remove_tag_attribute() to Utils.
- Tests: skip the sizes="auto" test before WP 6.7, compare attributes
  instead of exact markup, parse tags through get_media_tags(), cover
  the new code, and add an e2e case for the first image.
@PatelUtkarsh

Copy link
Copy Markdown
Contributor

Hello @gabrielcld2,

Which version will this PR ship in?

The PR adds a new filter (cloudinary_lazy_load_in_initial_viewport) and deprecates Video::filter_video_block_render_block(). Both are tagged 3.3.10 for now. so I am not sure if this PR goes into 3.5.0 or into a later release. Tell me the version and I will update the tags before I mark the PR ready for review.

@gabrielcld2

Copy link
Copy Markdown
Collaborator

@PatelUtkarsh We can include this in the 3.4.0 version

The new lazy load filter and the deprecated video callback ship in
3.4.0, not 3.3.10.
@utkarshcloudinary
utkarshcloudinary marked this pull request as ready for review December 3, 2026 10:01

@gabrielcld2 gabrielcld2 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is looking good. left some comments

Comment thread php/class-delivery.php
$has_cache = array();
$has_cache[ $type ] = $replacements;
update_post_meta( get_the_ID(), self::META_CACHE_KEY, $has_cache );
$this->update_context_cache( $type, $replacements );

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The above-the-fold decision depends on where the image sits on the page, but the result ends up in this cache, keyed only by the original tag. get_context_cache() then merges the caches of every post that went through the_post, so a decision made on one page gets reused on another:

  • Archives / blog home: each post's cache comes from its singular view, where its first image was eager. On an archive with 10 posts, the first image of post 8 is still served eager (no placeholder), even though it is far below the fold.
  • Related posts / query loops on a singular page: the same thing happens for the posts in the loop.
  • Mixed cached/uncached: cached tags skip rebuild_tag(), so they never increment viewport_count. An uncached image further down the page starts counting from 0 and can be made eager too.

Before this PR the lazy/eager result didn't depend on position, so caching the rebuilt tag was safe. Now it isn't.

A few options:

  1. Keep the viewport decision out of the cache. For example, cache the lazy version and apply the eager bypass when the replacements are applied.
  2. Don't cache img tags that went through the viewport check (simple, but we lose some of the cache benefit).
  3. Only apply the viewport check when the cache we read was written for the current post (is_singular() and the current queried object).

I don't mind which. What do you think?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, you're right. I had checked this on the blog home before, but only for images core marks loading="lazy" on the archive, where the tag differs and so does the cache key. Your case, where core leaves the tag the same and only our count differs, does leak.

Fixed in b6f8c3f with a mix of your options 1 and 2:

  • With the change for your other comment, an image core processed is decided from its own markup (fetchpriority, loading, or core's decoding="async" with no loading). The tag is the cache key, so that decision is safe to cache: when core decides differently on another page, the tag differs too.
  • Only the tags counted towards the threshold, and the tags whose result the cloudinary_lazy_load_in_initial_viewport filter changed, depend on the page. Those are now left out of _cld_replacements, so they are rebuilt on every page. That should also cover the mixed cached/uncached case, as a counted tag is never read from the cache, so it is always counted (I haven't tested that case separately).

Checked on the local site, with the post's cache cleared, then written by a visit to the single post: the blog home listing that post rendered exactly the same eager/lazy result as before the cache existed. Note this post's content images all come through core, so none of them is counted; the "counted tags are left out" part is covered by test_replacement_cache_skips_position_dependent_tags, not by this check.

} elseif ( 'lazy' === $loading || 'low' === $fetchpriority ) {
$in_viewport = false;
} else {
$in_viewport = $this->viewport_count < wp_omit_loading_attr_threshold();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question about the counting. This runs on the full output buffer, so header and template images (logo, site header image, menu icons…) use up the threshold before the content is reached. Core already made its own decision for the content images it processed: the first ones have no loading attribute and the rest got loading="lazy".

So with the default threshold of 3, a theme with a logo and two header images would lazy-load the first content image, which core had decided to load eagerly. In that case we do the opposite of what core decided, while the description says we use "the same signals as core".

Should an image with no loading attribute that core has already processed (e.g. it has a wp-image-* class and came through wp_filter_content_tags()) just be treated as eager, with the threshold counting used only for images core never saw? Or is it a deliberate choice to count document order across the whole page? Either way, a short note in the docblock would help.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, that wasn't deliberate. Fixed in b6f8c3f as you suggested: an image core already processed and left without a loading attribute is treated as eager, and doesn't count towards the threshold. Only images core never saw are counted.

To tell them apart I used core's decoding attribute instead of the wp-image-* class: by default core adds decoding="async" to the images it processes (wp_filter_content_tags() and wp_get_attachment_image()), and only decides loading for images with a width and height. If a site removes decoding with the wp_img_tag_add_decoding_attr filter, its images just fall back to being counted. So decoding + width + height + no loading means core left it eager. One exception: when wp_lazy_loading_enabled is off, core adds no loading anywhere, so those images are counted as before.

Checked with two header images printed on wp_body_open before the content, threshold 3:

  • before: the header images took two of the three eager places, so the third content image, which core had left without loading, was lazy loaded.
  • after: that image is eager. The header images are still eager, and the images core lazy loaded are still lazy.

The docblock of is_in_initial_viewport() now lists these rules.

Comment thread php/class-utils.php
$parsed['atts'][] = $name;
continue;
}
$parsed['atts'][ $name ] = (string) $value;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit / edge case: values are now decoded here, and HTML::build_tag() writes them back with esc_attr(), which does not double-encode existing entities. So a value that contains entity text gets decoded one level too far on the round trip. For example, alt="Use &amp;lt;img&amp;gt;" (an alt text that literally shows &lt;img&gt;) is decoded to Use &lt;img&gt;, and esc_attr() keeps it as is, so the browser now shows Use <img>.

It's a rare case and I wouldn't block on it, but since rebuild_tag() writes every attribute back, it might be worth either encoding the decoded values with double-encoding on (htmlspecialchars( $value, ENT_QUOTES, 'UTF-8', true )) when the tag is rebuilt, or adding a line about it in the Merge Danger section next to the backslash note.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in b6f8c3f. rebuild_tag() and process_featured_image() now escape the attribute values that are unchanged from the original tag with double encoding on (Utils::escape_original_attributes()), so alt="Use &amp;lt;img&amp;gt;" comes out the same as it went in. Values another filter changed (e.g. on cloudinary_pre_image_tag) are left as they are, as they may already be escaped, and so are values with no &.

There are 6 new unit tests across the three fixes. On the previous commit, 5 fail; the sixth (test_missing_loading_attribute_only_counts_as_core_decision_when_core_decided) guards the fallback case and passes on both. Unit tests (148), phpcs, PHPStan and the image, video, asset edit and breakpoints e2e specs (10 tests) pass locally.

- Treat an image core processed and left without a loading attribute
  as eager, without counting it. Core adds decoding="async" to every
  image it processes and only decides the loading of images with a
  width and height. Only images core never saw, such as header and
  template images, count towards the threshold. Before, a logo and
  header images used up the threshold and the first content image
  was lazy loaded against core's decision.
- Leave the counted tags, and tags whose result the viewport filter
  changed, out of the replacement cache. Their result depends on the
  page, and the cache of one post is reused on archives and loops.
- Escape attribute values that are unchanged from the original tag
  with double encoding on, so a value showing entity text, such as
  alt="Use &amp;lt;img&amp;gt;", is not decoded one level too far.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants