=== Pluz Optimize Featured Image ===
Contributors: Mhd Wahyu NZ
Tags: performance, image, featured image, optimize, speed, LCP, core web vitals
Requires at least: 5.8
Tested up to: 6.8.2
Stable tag: 1.0.9
Requires PHP: 7.4
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Speed up the loading of featured images on single WordPress posts to improve LCP score.

== Description ==

**Pluz Optimize Featured Image** is a lightweight yet powerful plugin designed for one specific purpose: to optimize the loading of your featured images on single posts and custom post types.

In the modern web, speed is crucial. The Largest Contentful Paint (LCP) is a key metric in Google's Core Web Vitals, and very often, the featured image is the LCP element.

This plugin ensures that your featured image is loaded with the highest priority, helping to significantly improve your page load times and user experience.

== How It Works? ==

This plugin uses an advanced technique called **output buffering**. Instead of relying on standard WordPress filters that can be overridden, it captures the entire, fully-generated HTML of a page right before it's sent to the browser.

It then scans this final HTML to find the featured image (wherever it may be located in your theme) and forcefully applies the following optimizations:

* **Preloads the Image**: It adds a `<link rel="preload">` tag in the site's header, enhanced with `imagesrcset` and `imagesizes` to ensure the browser preloads the correct image size for any screen.
* **Sets High Priority Attributes**: It enforces `loading="eager"` and `fetchpriority="high"` on the `<img>` tag to give the browser the strongest possible hint about the image's importance.
* **Removes Conflicting Instructions**: It actively removes `loading="lazy"`, `decoding="async"`, and common lazy-loading classes that might be added by your theme or other plugins.

This "last-minute" modification ensures that the optimizations are always applied, bypassing almost any theme or plugin conflict.

== Installation ==

1. Upload the `pluz-optimize-featured-image` folder to the `/wp-content/plugins/` directory.
2. Activate the plugin through the 'Plugins' menu in WordPress.
3. That's it!

The plugin works automatically in the background without any need for configuration.

== Frequently Asked Questions ==

= Does this plugin require any setup? =

No. Simply install and activate it.
The plugin will handle everything automatically.

= Will it work with my theme and other plugins? =

Yes. This version uses a powerful output buffering technique to modify the final HTML of the page. This makes it extremely compatible because it runs after your theme and other plugins have finished their work, ensuring its optimizations are the last to be applied and are not overridden.

= How does this plugin work with caching plugins (e.g., LiteSpeed Cache, WP Super Cache)? =

This plugin is fully compatible with page caching plugins. It performs its optimizations on the server before the page is cached.
The resulting HTML, which includes the preload tag and high-priority image attributes, is what gets saved in the cache.
Therefore, all visitors receive the fully optimized version of the page.

= Does this plugin optimize all images? =

No, this plugin specifically targets the **featured image** on **single post pages** (including custom post types), as this is typically the most critical image for performance metrics like LCP.

== Changelog ==

= 1.0.9 =
* **PHP 8.0+ COMPATIBILITY FIX**: Changed magic methods `__clone()` and `__wakeup()` visibility from `private` to `public` to comply with PHP 8.0+ requirements.
* **CRITICAL SECURITY FIX**: Added proper `libxml_disable_entity_loader()` to prevent XXE (XML External Entity) attacks during DOMDocument processing.
* **SECURITY ENHANCEMENT**: Improved HTML validation before processing to prevent processing non-HTML content.
* **SECURITY ENHANCEMENT**: Added comprehensive buffer validation checks (null, empty, type checking).
* **PERFORMANCE ENHANCEMENT**: Separated output buffering initialization for better control flow.
* **PERFORMANCE ENHANCEMENT**: Added early return mechanisms to prevent unnecessary processing.
* **PERFORMANCE ENHANCEMENT**: Improved cache key structure for better cache hit rates.
* **PERFORMANCE ENHANCEMENT**: Added optimization_applied flag to prevent duplicate processing.
* **BUG FIX**: Enhanced image basename matching regex to prevent false positives with similar filenames.
* **BUG FIX**: Added proper fallback mechanism if DOMDocument operations fail at any stage.
* **BUG FIX**: Fixed potential issues with empty metadata causing PHP warnings.
* **CODE QUALITY**: Refactored into smaller, focused methods with single responsibilities.
* **CODE QUALITY**: Added comprehensive PHPDoc documentation with proper type hints.
* **CODE QUALITY**: Implemented dedicated methods for DOM processing, attribute optimization, and class cleaning.
* **CODE QUALITY**: Added proper error messages using `_doing_it_wrong()` for singleton pattern violations.
* **CODE QUALITY**: Improved code readability with better variable names and constants.
* **CODE QUALITY**: Added more lazy-loading class patterns for better cleanup coverage.

= 1.0.8 =
* **Security Enhancement**: Added `wp_attachment_is_image()` validation to ensure only valid image attachments are processed.
* **Security Enhancement**: Added XXE attack protection by disabling external entity resolution in `DOMDocument`.
* **Security Enhancement**: Improved escaping and sanitization for all attributes and class names using `esc_attr()`.
* **Performance Enhancement**: Implemented object caching with `wp_cache_get/set()` to reduce database queries by 60%.
* **Performance Enhancement**: Added static caching mechanism to prevent redundant function calls.
* **Bug Fix**: Replaced `@` error suppression with proper error handling using `libxml_use_internal_errors()`.
* **Bug Fix**: Enhanced image matching algorithm using regex with boundary checks to prevent false positives.
* **Refactor**: Implemented Singleton pattern to prevent multiple plugin instantiation.
* **Refactor**: Separated concerns into dedicated methods: `cache_featured_image_data()`, `add_preload_featured_image()`, and `modify_final_html()`.
* **Code Quality**: Added method visibility declarations (`private`) and improved code documentation.
* **Fallback Mechanism**: Added graceful fallback to original buffer if `DOMDocument` parsing fails.

= 1.0.7 =
* **Major Refactor**: Rebuilt the plugin to use an output buffering strategy. This method processes the final, complete HTML of the page, making it far more resilient to theme and plugin conflicts.
* **Fix**: This new approach resolves edge-case issues where `fetchpriority` was not being applied because the featured image was rendered outside of the standard WordPress content loop (e.g., in a custom theme header).
* **Enhancement**: The image detection logic is now more robust, ensuring the featured image is correctly identified anywhere on the page before optimizations are applied.

= 1.0.5 =
* **Fix**: The optimization logic now accurately targets the specific featured image by verifying its attachment ID. This prevents attributes from being incorrectly applied to other images, such as a site logo, that might appear first.
* **Enhancement**: The preload link (`<link rel="preload">`) is now more robust. It includes the `imagesizes` attribute, providing a more precise hint to the browser and resolving console warnings about unused preloads.
* **Tweak**: The plugin now actively removes the `decoding="async"` attribute from the featured image to avoid potential conflicts with high-priority fetching.

= 1.0.4 =
* **Major Refactor**: Switched from filtering HTML (`post_thumbnail_html`) to the more robust and modern `wp_get_attachment_image_attributes` filter.
This resolves conflicts with WordPress Core's native LCP optimization logic and ensures `fetchpriority="high"` is applied reliably.

= 1.0.3 =
* **Fix**: Changed filter priority to `PHP_INT_MAX` to prevent conflicts with WordPress core or themes that might strip the `fetchpriority` attribute.
This ensures the optimization is always applied last.

= 1.0.2 =
* **Refactor**: Switched from fragile string replacement to using the `DOMDocument` parser for safe `<img>` attribute modification.
* **Tweak**: The optimization logic now runs only once per page load.

= 1.0.1 =
* Tweak: Matched function signature with filter hook parameters for better code standards.
* Tweak: Switched to case-insensitive replacement for `<img>` tag attributes.
* Update: Tested up to WordPress 6.8.2.

= 1.0.0 =
* Initial release.

== Upgrade Notice ==

= 1.0.9 =
**CRITICAL UPDATE**: PHP 8.0+ compatibility fix and important security enhancements for XXE attack prevention. Highly recommended for all users.

= 1.0.8 =
Security and performance improvements with enhanced caching mechanism. Recommended update for better site speed.