Enhance AI Vision Support in SEO Press Pro with Smart Image Optimization

  • This code snippet upgrades SEO Press Pro by improving how image files are processed for OpenAI’s image recognition system.


    🚫 The Problem

    OpenAI's vision system does not support these image formats:

    • SVG (Scalable Vector Graphics)
    • HEIC (High-Efficiency Image Codec)
    • AVIF (AV1 Image File Format)

    Additionally, large, unoptimized images consume more tokens during analysis, leading to higher costs and slower response times.


    ✅ What This Snippet Does

    1. Format Conversion
      Automatically converts unsupported formats (e.g., AVIF, HEIC, SVG) to WebP, ensuring compatibility with AI models.
    2. Image Resizing
      Resizes images to a maximum width of 1024px, reducing file size and token usage for faster AI processing.
    3. Metadata Stripping
      Removes unnecessary EXIF and metadata to further minimize file size and improve privacy.
    4. Efficient Compression
      Applies lightweight compression (e.g., WebP at 85% quality) while preserving transparency and visual clarity.
    5. Legacy Formats
      Handles legacy formats like BMP, TIFF

    🔁 Smart Fallback Logic

    • If WebP isn’t supported → falls back to JPEG
    • If Imagick isn’t available → uses GD as a fallback library
    • If format is unknown → applies generic conversion logic
  • Snippet

    <?php
    /**
    * Universal Image to WebP Converter for SEO Press Pro AI Alt Text Generation
    * Converts all image formats (AVIF, JPEG, PNG, GIF, etc.) to optimized WebP
    */

    // --- Debugging Control ---
    // To enable debug logging, define SEOPRESS_IMAGE_CONVERTER_DEBUG as true in your wp-config.php or theme's functions.php
    // Example: define('SEOPRESS_IMAGE_CONVERTER_DEBUG', true);
    // By default, debugging is OFF if the constant is not defined or is false.
    if (!defined('SEOPRESS_IMAGE_CONVERTER_DEBUG')) {
    define('SEOPRESS_IMAGE_CONVERTER_DEBUG', false); // Default to false (no debugging)
    }

    // Helper function for conditional logging
    function seopress_image_converter_log($message) {
    if (SEOPRESS_IMAGE_CONVERTER_DEBUG) {
    error_log($message);
    }
    }

    // Cache for converted images to avoid repeated processing
    class ImageConverterCache {
    private static $cache = [];
    private static $cache_duration = 3600; // 1 hour

    public static function get($key) {
    if (isset(self::$cache[$key])) {
    $data = self::$cache[$key];
    if (time() - $data['timestamp'] < self::$cache_duration) {
    return $data['value'];
    }
    unset(self::$cache[$key]);
    }
    return false;
    }

    public static function set($key, $value) {
    self::$cache[$key] = [
    'value' => $value,
    'timestamp' => time()
    ];
    }
    }

    // Main hooks - consolidated for efficiency
    add_filter('seopress_pro_ai_completion_image_data', 'convert_image_to_webp_for_ai', 10, 2);
    add_filter('seopress_ai_completion_image_data', 'convert_image_to_webp_for_ai', 10, 2);
    add_filter('pre_http_request', 'intercept_openai_requests_webp', 10, 3);

    function convert_image_to_webp_for_ai($image_data, $attachment_id) {
    if (!$attachment_id || !wp_attachment_is_image($attachment_id)) {
    return $image_data;
    }

    // Check cache first
    $cache_key = 'webp_convert_' . $attachment_id . '_' . get_post_modified_time('U', true, $attachment_id);
    $cached_result = ImageConverterCache::get($cache_key);
    if ($cached_result !== false) {
    seopress_image_converter_log('Using cached WebP conversion for attachment: ' . $attachment_id);
    return $cached_result;
    }

    $result = get_optimal_webp_for_ai($attachment_id);

    // Cache the result
    if ($result) {
    ImageConverterCache::set($cache_key, $result);
    }

    return $result ?: $image_data;
    }

    function get_optimal_webp_for_ai($attachment_id) {
    // Check WebP support first
    if (!webp_support_available()) {
    seopress_image_converter_log('WebP support not available, falling back to JPEG');
    return get_optimal_jpeg_for_ai($attachment_id);
    }

    $image_url = wp_get_attachment_url($attachment_id);
    $mime_type = get_post_mime_type($attachment_id);

    seopress_image_converter_log("Converting image to WebP - ID: {$attachment_id}, Type: {$mime_type}");

    // Handle different image types
    switch ($mime_type) {
    case 'image/avif':
    return convert_avif_to_webp($attachment_id);
    case 'image/jpeg':
    case 'image/jpg':
    return convert_jpeg_to_webp($attachment_id);
    case 'image/png':
    return convert_png_to_webp($attachment_id);
    case 'image/gif':
    return convert_gif_to_webp($attachment_id);
    case 'image/webp':
    return optimize_existing_webp($attachment_id);
    case 'image/bmp':
    case 'image/tiff':
    case 'image/svg+xml': // Note: SVG to WebP conversion might rasterize. Consider implications.
    return convert_generic_to_webp($attachment_id);
    default:
    seopress_image_converter_log("Unsupported image type: {$mime_type}");
    return false;
    }
    }

    function webp_support_available() {
    // Check if WebP is supported
    if (function_exists('imagewebp')) {
    return true; // GD support
    }

    if (class_exists('Imagick')) {
    try {
    $imagick = new Imagick();
    $formats = $imagick->queryFormats('WEBP');
    return !empty($formats);
    } catch (Exception $e) {
    seopress_image_converter_log("Imagick WebP support check failed: " . $e->getMessage());
    // Continue to check other methods
    }
    }

    return false;
    }

    function convert_avif_to_webp($attachment_id) {
    $image_path = get_attached_file($attachment_id);
    if (!$image_path || !file_exists($image_path)) {
    seopress_image_converter_log("AVIF conversion: Original file not found for attachment ID {$attachment_id}. Path: {$image_path}");
    return false;
    }

    // Try ImageMagick first (better AVIF support)
    if (class_exists('Imagick')) {
    return convert_with_imagick_to_webp($image_path, 'avif', $attachment_id);
    }

    // Fallback to GD (PHP 8.1+)
    if (function_exists('imagecreatefromavif')) {
    return convert_with_gd_to_webp($image_path, 'avif', $attachment_id);
    }

    seopress_image_converter_log('No AVIF support available for conversion.');
    return false;
    }

    function convert_jpeg_to_webp($attachment_id) {
    return convert_standard_format_to_webp($attachment_id, 'jpeg');
    }

    function convert_png_to_webp($attachment_id) {
    return convert_standard_format_to_webp($attachment_id, 'png');
    }

    function convert_gif_to_webp($attachment_id) {
    // Note: This converts first frame of animated GIFs
    return convert_standard_format_to_webp($attachment_id, 'gif');
    }

    function convert_generic_to_webp($attachment_id) {
    // This function handles types like BMP, TIFF.
    // SVG to WebP will rasterize; ensure this is the desired behavior.
    return convert_standard_format_to_webp($attachment_id, 'generic');
    }

    function optimize_existing_webp($attachment_id) {
    // WebP is already optimal format, just resize if needed
    return convert_standard_format_to_webp($attachment_id, 'webp');
    }

    function convert_standard_format_to_webp($attachment_id, $source_format) {
    // Try to find optimal existing size first
    $optimal_path = find_optimal_size_path($attachment_id);

    if ($optimal_path && file_exists($optimal_path)) {
    seopress_image_converter_log("Using optimal size '{$optimal_path}' for attachment ID {$attachment_id} (format: {$source_format})");
    if (class_exists('Imagick')) {
    return convert_with_imagick_to_webp($optimal_path, $source_format, $attachment_id);
    } else {
    return convert_with_gd_to_webp($optimal_path, $source_format, $attachment_id);
    }
    }
    seopress_image_converter_log("No optimal size found for attachment ID {$attachment_id}. Using original.");

    // If no optimal size exists, create one from original
    $original_path = get_attached_file($attachment_id);
    if ($original_path && file_exists($original_path)) {
    seopress_image_converter_log("Using original file '{$original_path}' for attachment ID {$attachment_id} (format: {$source_format})");
    if (class_exists('Imagick')) {
    return convert_with_imagick_to_webp($original_path, $source_format, $attachment_id);
    } else {
    return convert_with_gd_to_webp($original_path, $source_format, $attachment_id);
    }
    }
    seopress_image_converter_log("Original file not found for attachment ID {$attachment_id}. Path: {$original_path}");
    return false;
    }

    function find_optimal_size_path($attachment_id) {
    // Preferred sizes for AI vision (in order)
    $preferred_sizes = ['medium_large', 'large', 'medium'];

    foreach ($preferred_sizes as $size) {
    $image_src_data = wp_get_attachment_image_src($attachment_id, $size);
    if (!$image_src_data) continue;

    $image_url = $image_src_data[0];
    $image_path = get_image_path_from_url($image_url);

    if (!$image_path || !file_exists($image_path)) {
    seopress_image_converter_log("Optimal size check: Path '{$image_path}' (from URL '{$image_url}') for size '{$size}' does not exist for attachment ID {$attachment_id}.");
    continue;
    }

    $dimensions = [$image_src_data[1], $image_src_data[2]];
    $file_size = filesize($image_path);

    if (is_optimal_for_vision($dimensions, $file_size)) {
    seopress_image_converter_log("Found optimal size '{$size}' at path '{$image_path}' for attachment ID {$attachment_id}.");
    return $image_path;
    }
    }
    seopress_image_converter_log("No predefined optimal size found for attachment ID {$attachment_id}. Will use original if available.");
    return false; // Return false if no suitable size is found
    }


    function convert_with_imagick_to_webp($image_path, $source_format, $attachment_id = 'N/A') {
    try {
    $imagick = new Imagick();

    // For some formats like AVIF, it's better to read the file path directly
    if ($source_format === 'avif' || $source_format === 'webp' || PHP_VERSION_ID < 80100 && $source_format === 'avif') { // PHP < 8.1 might not have AVIF support in GD
    if (!$imagick->readImage($image_path)) {
    seopress_image_converter_log("ImageMagick failed to read {$source_format} file: {$image_path} for attachment ID {$attachment_id}");
    return false;
    }
    } else {
    // For other formats, using file_get_contents can be more reliable with some Imagick builds
    $file_contents = file_get_contents($image_path);
    if ($file_contents === false) {
    seopress_image_converter_log("ImageMagick: Failed to get contents of {$image_path} for attachment ID {$attachment_id}");
    return false;
    }
    if (!$imagick->readImageBlob($file_contents)) {
    seopress_image_converter_log("ImageMagick failed to read image blob for {$source_format} file: {$image_path} for attachment ID {$attachment_id}");
    return false;
    }
    }


    $width = $imagick->getImageWidth();
    $height = $imagick->getImageHeight();

    // Resize to optimal dimensions (1024px max dimension)
    $target_size = 1024;
    if (max($width, $height) > $target_size) {
    $imagick->resizeImage($target_size, $target_size, Imagick::FILTER_LANCZOS, 1, true);
    seopress_image_converter_log("ImageMagick: Resized image for attachment ID {$attachment_id} to fit within {$target_size}px.");
    }

    // Convert to WebP with optimal settings
    $imagick->setImageFormat('webp');
    $imagick->setImageCompressionQuality(85); // Good balance of quality/size
    $imagick->setOption('webp:lossless', 'false');
    $imagick->setOption('webp:alpha-quality', '95'); // Higher quality for alpha channel

    // Strip metadata to reduce size
    $imagick->stripImage();

    $image_blob = $imagick->getImageBlob();
    $imagick->destroy();

    if ($image_blob) {
    seopress_image_converter_log("Successfully converted {$source_format} to WebP with ImageMagick for attachment ID {$attachment_id}. Original path: {$image_path}");
    return 'data:image/webp;base64,' . base64_encode($image_blob);
    } else {
    seopress_image_converter_log("ImageMagick conversion to WebP resulted in empty blob for {$source_format}, attachment ID {$attachment_id}. Path: {$image_path}");
    }

    } catch (Exception $e) {
    seopress_image_converter_log("ImageMagick WebP conversion error ({$source_format}) for attachment ID {$attachment_id}: " . $e->getMessage() . ". Path: {$image_path}");
    }

    return false;
    }

    function convert_with_gd_to_webp($image_path, $source_format, $attachment_id = 'N/A') {
    try {
    $image = null;
    // Create image resource based on source format
    switch ($source_format) {
    case 'jpeg':
    case 'jpg': // Added jpg as an alias
    $image = @imagecreatefromjpeg($image_path);
    break;
    case 'png':
    $image = @imagecreatefrompng($image_path);
    break;
    case 'gif':
    $image = @imagecreatefromgif($image_path);
    break;
    case 'webp':
    $image = @imagecreatefromwebp($image_path);
    break;
    case 'avif':
    if (function_exists('imagecreatefromavif')) {
    $image = @imagecreatefromavif($image_path);
    } else {
    seopress_image_converter_log("GD: imagecreatefromavif function does not exist. Cannot convert AVIF for attachment ID {$attachment_id}.");
    return false;
    }
    break;
    case 'bmp':
    if (function_exists('imagecreatefrombmp')) {
    $image = @imagecreatefrombmp($image_path);
    } else {
    // Try generic if specific function not available
    $image_contents = file_get_contents($image_path);
    if ($image_contents) $image = @imagecreatefromstring($image_contents);
    if (!$image) seopress_image_converter_log("GD: imagecreatefrombmp function does not exist, and imagecreatefromstring failed for BMP. Attachment ID {$attachment_id}.");
    else seopress_image_converter_log("GD: imagecreatefrombmp not available, used imagecreatefromstring for BMP. Attachment ID {$attachment_id}.");
    }
    break;
    default: // Handles 'generic' and other types if imagecreatefromstring supports them
    $image_contents = file_get_contents($image_path);
    if ($image_contents) {
    $image = @imagecreatefromstring($image_contents);
    }
    if (!$image) {
    seopress_image_converter_log("GD: Failed to create image resource using imagecreatefromstring for {$source_format}, attachment ID {$attachment_id}. Path: {$image_path}");
    }
    break;
    }

    if (!$image) {
    seopress_image_converter_log("GD: Failed to create image resource from {$source_format} for attachment ID {$attachment_id}. Path: {$image_path}");
    return false;
    }

    $width = imagesx($image);
    $height = imagesy($image);

    // Resize if needed
    $target_size = 1024;
    $max_dimension = max($width, $height);

    if ($max_dimension > $target_size) {
    $ratio = $target_size / $max_dimension;
    $new_width = round($width * $ratio);
    $new_height = round($height * $ratio);

    $resized = imagecreatetruecolor($new_width, $new_height);
    if (!$resized) {
    seopress_image_converter_log("GD: Failed to create truecolor image for resizing. Attachment ID {$attachment_id}.");
    imagedestroy($image);
    return false;
    }


    // Preserve transparency for PNG/GIF/WebP (source)
    if (in_array($source_format, ['png', 'gif', 'webp'])) {
    imagealphablending($resized, false);
    imagesavealpha($resized, true);
    $transparent_index = imagecolorallocatealpha($resized, 255, 255, 255, 127);
    if ($transparent_index !== false) {
    imagefill($resized, 0, 0, $transparent_index);
    } else {
    seopress_image_converter_log("GD: Failed to allocate transparent color for resizing. Attachment ID {$attachment_id}.");
    }
    }

    imagecopyresampled($resized, $image, 0, 0, 0, 0,
    $new_width, $new_height, $width, $height);

    imagedestroy($image);
    $image = $resized;
    seopress_image_converter_log("GD: Resized image for attachment ID {$attachment_id} to {$new_width}x{$new_height}.");
    }

    // Convert to WebP
    ob_start();
    $success = imagewebp($image, null, 85); // 85% quality
    $image_data_blob = ob_get_contents();
    ob_end_clean();

    imagedestroy($image);

    if ($success && $image_data_blob) {
    seopress_image_converter_log("Successfully converted {$source_format} to WebP with GD for attachment ID {$attachment_id}. Original path: {$image_path}");
    return 'data:image/webp;base64,' . base64_encode($image_data_blob);
    } else {
    seopress_image_converter_log("GD imagewebp conversion failed or produced no data for {$source_format}, attachment ID {$attachment_id}. Path: {$image_path}");
    }

    } catch (Exception $e) {
    seopress_image_converter_log("GD WebP conversion error ({$source_format}) for attachment ID {$attachment_id}: " . $e->getMessage() . ". Path: {$image_path}");
    }

    return false;
    }


    function get_optimal_jpeg_for_ai($attachment_id) {
    seopress_image_converter_log("Falling back to JPEG for attachment ID {$attachment_id} as WebP is not available/supported.");
    // Fallback to JPEG if WebP not available
    $optimal_path = find_optimal_size_path($attachment_id);

    if (!$optimal_path) {
    $original_path = get_attached_file($attachment_id);
    if ($original_path && file_exists($original_path)) {
    $optimal_path = $original_path;
    seopress_image_converter_log("JPEG Fallback: No optimal size found, using original: {$optimal_path} for attachment ID {$attachment_id}.");
    } else {
    seopress_image_converter_log("JPEG Fallback: Original file not found for attachment ID {$attachment_id}. Path: {$original_path}");
    return false;
    }
    } else {
    seopress_image_converter_log("JPEG Fallback: Using optimal path: {$optimal_path} for attachment ID {$attachment_id}.");
    }


    // Use WordPress image editor for JPEG fallback
    $image_editor = wp_get_image_editor($optimal_path);
    if (is_wp_error($image_editor)) {
    seopress_image_converter_log("JPEG Fallback: WP_Image_Editor error for attachment ID {$attachment_id}: " . $image_editor->get_error_message() . ". Path: {$optimal_path}");
    return false;
    }

    $current_size = $image_editor->get_size();
    if (empty($current_size) || !isset($current_size['width']) || !isset($current_size['height'])) {
    seopress_image_converter_log("JPEG Fallback: Could not get image size for attachment ID {$attachment_id}. Path: {$optimal_path}");
    return false;
    }
    $max_dimension = max($current_size['width'], $current_size['height']);

    if ($max_dimension > 1024) {
    $image_editor->resize(1024, 1024, false); // Resize maintaining aspect ratio
    seopress_image_converter_log("JPEG Fallback: Resized image for attachment ID {$attachment_id} to fit within 1024px. Path: {$optimal_path}");
    }

    // Set JPEG quality
    $image_editor->set_quality(82); // Standard WordPress JPEG quality

    $temp_file = wp_tempnam($optimal_path); // Create temp file in the same directory if possible for permissions
    if (!$temp_file) {
    seopress_image_converter_log("JPEG Fallback: Could not create temp file for attachment ID {$attachment_id}.");
    return false;
    }

    $saved_image = $image_editor->save($temp_file, 'image/jpeg');

    if (is_wp_error($saved_image)) {
    seopress_image_converter_log("JPEG Fallback: Error saving resized JPEG for attachment ID {$attachment_id}: " . $saved_image->get_error_message() . ". Temp file: {$temp_file}");
    @unlink($temp_file); // Attempt to clean up
    return false;
    }

    $image_data_blob = file_get_contents($temp_file);
    @unlink($temp_file); // Clean up temp file

    if ($image_data_blob) {
    seopress_image_converter_log("JPEG Fallback: Successfully processed image for attachment ID {$attachment_id}. Path: {$optimal_path}");
    return 'data:image/jpeg;base64,' . base64_encode($image_data_blob);
    } else {
    seopress_image_converter_log("JPEG Fallback: Failed to get contents of saved JPEG for attachment ID {$attachment_id}. Path: {$optimal_path}");
    }

    return false;
    }


    function intercept_openai_requests_webp($response, $parsed_args, $url) {
    if (strpos($url, 'api.openai.com') === false || !isset($parsed_args['body'])) {
    return $response;
    }

    $body_json = $parsed_args['body'];
    // Check if body is already an array (e.g. from other hooks)
    if (is_string($body_json)) {
    $body = json_decode($body_json, true);
    } elseif (is_array($body_json)) {
    $body = $body_json; // Already decoded
    } else {
    seopress_image_converter_log('OpenAI Intercept: Parsed body is not a string or array.');
    return $response;
    }


    if (json_last_error() !== JSON_ERROR_NONE || !$body || !isset($body['messages'])) {
    seopress_image_converter_log('OpenAI Intercept: Failed to decode JSON body or messages not set. Error: ' . json_last_error_msg());
    return $response;
    }

    $modified = false;

    foreach ($body['messages'] as &$message) { // Use reference to modify original array
    if (!isset($message['content']) || !is_array($message['content'])) {
    continue;
    }

    foreach ($message['content'] as &$content_item) { // Use reference
    if (isset($content_item['type']) && $content_item['type'] === 'image_url' &&
    isset($content_item['image_url']['url']) &&
    strpos($content_item['image_url']['url'], 'data:') !== 0) { // Ensure it's an actual URL, not data URI

    $image_url_to_convert = $content_item['image_url']['url'];
    seopress_image_converter_log("OpenAI Intercept: Found image URL to potentially convert: {$image_url_to_convert}");

    $attachment_id = get_attachment_id_from_url($image_url_to_convert);
    if ($attachment_id) {
    seopress_image_converter_log("OpenAI Intercept: Attachment ID {$attachment_id} found for URL: {$image_url_to_convert}");
    $webp_image_data_uri = get_optimal_webp_for_ai($attachment_id); // This function now returns data URI or false

    if ($webp_image_data_uri) {
    $content_item['image_url']['url'] = $webp_image_data_uri;
    $modified = true;
    seopress_image_converter_log("OpenAI Intercept: Successfully replaced image URL with WebP data URI for attachment ID {$attachment_id}.");
    } else {
    seopress_image_converter_log("OpenAI Intercept: Failed to convert image to WebP for attachment ID {$attachment_id}. Original URL kept.");
    }
    } else {
    seopress_image_converter_log("OpenAI Intercept: No attachment ID found for URL: {$image_url_to_convert}");
    }
    }
    }
    }
    unset($content_item); // Unset reference
    unset($message); // Unset reference


    if ($modified) {
    $parsed_args['body'] = json_encode($body);
    if (json_last_error() !== JSON_ERROR_NONE) {
    seopress_image_converter_log('OpenAI Intercept: Failed to re-encode JSON body after modification. Error: ' . json_last_error_msg());
    return $response; // Return original response if re-encoding fails
    }
    seopress_image_converter_log('OpenAI Intercept: Body modified, making new wp_remote_request.');
    // To avoid potential infinite loops if wp_remote_request itself triggers this filter again,
    // we might need to remove and re-add the filter, or use a flag.
    // For simplicity here, assuming it won't loop. If issues, this is a place to check.
    remove_filter('pre_http_request', 'intercept_openai_requests_webp', 10);
    $new_response = wp_remote_request($url, $parsed_args);
    add_filter('pre_http_request', 'intercept_openai_requests_webp', 10, 3);
    return $new_response;
    }

    return $response;
    }

    // Helper functions
    function is_optimal_for_vision($dimensions, $file_size) {
    if (!is_array($dimensions) || count($dimensions) < 2) return false;
    $width = $dimensions[0];
    $height = $dimensions[1];
    $max_dimension = max($width, $height);

    // OpenAI Vision API recommendations:
    // - Images are best between 512px and 2048px on their shortest side.
    // - Max file size is 20MB, but smaller is faster. We aim for < 5MB.
    // We'll check the longest side against a reasonable upper bound (e.g. 2048px)
    // and shortest side against a lower bound (e.g. 512px).
    $min_dimension = min($width, $height);

    $is_within_dimensions = ($min_dimension >= 512 && $max_dimension 0 && $file_size my-image.jpg
    // Example: my-image-150x150.jpg -> my-image.jpg
    $filename_pattern = preg_replace('/(-d+xd+).(jpe?g|png|gif|webp)$/i', '.$2', basename($file_path)); // remove -150x150
    $filename_pattern = preg_replace('/(-scaled|-rotated).(jpe?g|png|gif|webp)$/i', '.$2', $filename_pattern); // remove -scaled / -rotated

    // Search for the attachment ID using the _wp_attached_file meta key
    // We search for a meta_value that ENDS WITH the derived filename pattern.
    // This is because _wp_attached_file stores the path relative to the year/month uploads folder.
    // e.g., 2023/05/my-image.jpg
    $sql = $wpdb->prepare(
    "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value LIKE %s",
    '%' . $wpdb->esc_like(dirname($file_path) . '/' . $filename_pattern) // Try with full relative path first
    );
    $found_id = $wpdb->get_var($sql);

    if ($found_id) {
    seopress_image_converter_log("Fallback found attachment ID {$found_id} for URL {$url} using path pattern.");
    return $found_id;
    }

    // If not found, try matching only the filename, in case the directory structure in URL is different
    $sql_filename_only = $wpdb->prepare(
    "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value LIKE %s",
    '%' . $wpdb->esc_like($filename_pattern)
    );
    $found_id_filename_only = $wpdb->get_var($sql_filename_only);

    if ($found_id_filename_only) {
    seopress_image_converter_log("Fallback found attachment ID {$found_id_filename_only} for URL {$url} using filename pattern only.");
    return $found_id_filename_only;
    }

    seopress_image_converter_log("Fallback could not find attachment ID for URL: {$url}");
    return false;
    }


    // System compatibility check
    add_action('admin_notices', function() {
    if (!webp_support_available()) {
    echo 'SEO Press Image Converter: WebP support (GD or ImageMagick) not detected on your server. The plugin will attempt to fall back to JPEG for AI processing, but WebP is recommended for optimal performance and quality. Please consider installing/enabling the ImageMagick extension with WebP support, or ensure your PHP GD extension is compiled with WebP support (usually available in PHP 8.0+).';
    }
    });

    // Initial debug log to confirm loading and WebP support status
    add_action('init', function() {
    if (SEOPRESS_IMAGE_CONVERTER_DEBUG) { // Check the constant
    $webp_support_status = webp_support_available() ? 'YES' : 'NO';
    $gd_available = function_exists('gd_info') ? 'YES' : 'NO';
    $imagick_available = class_exists('Imagick') ? 'YES' : 'NO';
    seopress_image_converter_log("Universal Image to WebP converter loaded. Debugging ENABLED. WebP Support: {$webp_support_status}. GD: {$gd_available}. ImageMagick: {$imagick_available}.");
    }
    }, 0); // Run early on init

    ?>
Review Your Cart
0
Add Coupon Code
Subtotal