Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Last active May 21, 2024 12:20
Show Gist options
  • Save wpmudev-sls/aa58d581efe31238ca88734c99158596 to your computer and use it in GitHub Desktop.
Save wpmudev-sls/aa58d581efe31238ca88734c99158596 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Fix re-check loop while local webp active
* Description: Overrides the should_reoptimize method to fix WebP missing files issue.
* Jira: SLS-6099, SMUSH-1557
* Author: Abdoljabbar Bakhshande
* Author URI: https://wpmudev.com
* License: GPLv2 or later
*
* @package WebP_Missing_Files_Fix
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Fix WP Smush WebP optimization issue.
*/
function fix_wp_smush_webp_optimization() {
// Check if Smush Pro is active and its version.
if ( ! class_exists( 'WP_Smush' ) || ( defined( 'WP_SMUSH_VERSION' ) && version_compare( WP_SMUSH_VERSION, '3.17.1', '>=' ) ) ) {
return;
}
// Define the file path of the file to be modified.
$file_path = WP_PLUGIN_DIR . '/wp-smush-pro/core/webp/class-webp-optimization.php';
// Check if the file exists.
if ( file_exists( $file_path ) ) {
// Get the MD5 hash of the current file.
$current_md5 = md5_file( $file_path );
// Get the MD5 hash of the file during the last run.
$old_md5 = get_option( 'wp_smush_webp_optimization_fix_md5' );
// If the MD5 hash of the current file is different from the old one, update the file.
if ( $current_md5 !== $old_md5 ) {
// Get the contents of the file.
$file_contents = file_get_contents( $file_path );
// Check if the file contains the code to be replaced.
if ( false !== strpos( $file_contents, 'if ( ! $this->fs->file_exists( $webp_file_path ) ) {' ) ) {
// Replace the code using preg_replace().
$pattern = '/if \( \! \$this->fs->file_exists\( \$webp_file_path \) \) \{\s*return true;\s*\}/s';
$replacement = 'if ( $this->fs->file_exists( $webp_file_path ) ) {
return false;
}';
$updated_contents = preg_replace( $pattern, $replacement, $file_contents );
// Write the updated contents back to the file.
file_put_contents( $file_path, $updated_contents );
// Get the MD5 hash of the updated file.
$updated_md5 = md5_file( $file_path );
// Update the MD5 hash of the file in the database.
update_option( 'wp_smush_webp_optimization_fix_md5', $updated_md5 );
}
}
}
}
add_action( 'plugins_loaded', 'fix_wp_smush_webp_optimization' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment