options = get_option('aio_options', []); // 1. WebP Auto Conversion (Background Processing) if ( !empty($this->options['opt-perf-webp']) ) { add_filter('wp_generate_attachment_metadata', [$this, 'schedule_webp_conversion'], 10, 2); add_action('aio_convert_webp_cron', [$this, 'process_webp_conversion']); } // 2. Force Native Lazy Load if ( !empty($this->options['opt-perf-lazyload']) ) { add_filter( 'wp_lazy_loading_enabled', '__return_true' ); add_filter( 'the_content', [$this, 'force_lazy_load_content'], 99 ); } // 3. Minify HTML/CSS/JS if ( !empty($this->options['optEnableMinify']) ) { add_action('template_redirect', [$this, 'start_minify_buffer'], 1); } $is_third_party_seo = defined('WPSEO_VERSION') || defined('RANK_MATH_VERSION') || class_exists('All_in_One_SEO_Pack'); if ( !$is_third_party_seo ) { // 7. Auto Meta Tags if ( !empty($this->options['optEnableMetaTags']) ) { add_action('wp_head', [$this, 'generate_meta_tags'], 1); } // 8. Social Open Graph if ( !empty($this->options['optEnableOpenGraph']) ) { add_filter('language_attributes', [$this, 'add_og_xml_ns']); add_action('wp_head', [$this, 'generate_open_graph'], 2); } // 9. XML Sitemap Generator if ( !empty($this->options['optEnableSitemap']) ) { add_action('init', [$this, 'register_sitemap_rewrite']); add_action('template_redirect', [$this, 'render_sitemap'], 1); } } // 5. Auto Alt Tags if ( !empty($this->options['optEnableAutoAltTags']) ) { add_filter('wp_get_attachment_image_attributes', [$this, 'auto_fill_alt_tags'], 10, 3); } // 6. Media Replace if ( !empty($this->options['optEnableMediaReplace']) ) { add_filter('attachment_fields_to_edit', [$this, 'add_media_replace_field'], 10, 2); add_action('edit_attachment', [$this, 'process_media_replace']); } } /** * Schedule the conversion to run asynchronously via WP Cron. */ public function schedule_webp_conversion($meta, $attachment_id) { // Schedule event 5 seconds from now to avoid blocking the current upload request if (!wp_next_scheduled('aio_convert_webp_cron', [$attachment_id])) { wp_schedule_single_event(time() + 5, 'aio_convert_webp_cron', [$attachment_id]); } return $meta; } /** * Process the WebP conversion in the background. */ public function process_webp_conversion($attachment_id) { $delete_original = !empty($this->options['opt-perf-webp-delete-original']); aio_generate_webp_for_attachment($attachment_id, $delete_original); } /** * Fallback to add loading="lazy" to all img/iframe tags in content if missing. */ public function force_lazy_load_content($content) { if (empty($content) || !is_string($content)) return $content; // Add loading="lazy" to tags that don't have it $content = preg_replace_callback( '/<(img|iframe)[^>]+>/i', function($matches) { $tag = $matches[0]; if (stripos($tag, 'loading=') === false) { $tag = str_replace('<' . $matches[1], '<' . $matches[1] . ' loading="lazy"', $tag); } return $tag; }, $content ); return $content; } /** * Start Output Buffer for Minification */ public function start_minify_buffer() { if (!is_admin() && !is_user_logged_in()) { ob_start([$this, 'minify_html_output']); } } /** * Regex Minify Logic for HTML/CSS/JS */ public function minify_html_output($buffer) { if (empty($buffer)) return $buffer; $search = array( '/\>[^\S ]+/s', // strip whitespaces after tags, except space '/[^\S ]+\/' // Remove HTML comments ); $replace = array( '>', '<', '\\1', '' ); $buffer = preg_replace($search, $replace, $buffer); return $buffer; } /** * Auto Fill Alt Tags */ public function auto_fill_alt_tags($attr, $attachment, $size) { if (empty($attr['alt'])) { $attr['alt'] = trim(wp_strip_all_tags(get_the_title($attachment->ID))); if (empty($attr['alt'])) { // Fallback to parent post title $parent_id = wp_get_post_parent_id($attachment->ID); if ($parent_id) { $attr['alt'] = trim(wp_strip_all_tags(get_the_title($parent_id))); } } } return $attr; } /** * Add Media Replace Field */ public function add_media_replace_field($form_fields, $post) { // Only show in the traditional Edit Media screen if (function_exists('get_current_screen')) { $screen = get_current_screen(); if ($screen && $screen->id === 'attachment') { $html = '

'; $html .= '

' . esc_html__('Upload a new file to replace the current one. Note: The old file will be deleted permanently.', 'aio-tools') . '

'; $html .= wp_nonce_field('aio_media_replace_action', 'aio_media_replace_nonce', true, false); $form_fields['aio_media_replace'] = array( 'label' => __('Replace File', 'aio-tools'), 'input' => 'html', 'html' => $html ); } } return $form_fields; } /** * Process Media Replace Upload */ public function process_media_replace($attachment_id) { if (!empty($_FILES['aio_media_replace']['name'])) { if (!isset($_POST['aio_media_replace_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aio_media_replace_nonce'])), 'aio_media_replace_action')) { return; } require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); $uploaded_file = $_FILES['aio_media_replace']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized $upload_overrides = array('test_form' => false); $old_file = get_attached_file($attachment_id); $movefile = wp_handle_upload($uploaded_file, $upload_overrides); if ($movefile && !isset($movefile['error'])) { // Delete old file if ($old_file && file_exists($old_file)) { wp_delete_file($old_file); } $new_file = $movefile['file']; global $wpdb; $wpdb->update($wpdb->posts, ['post_mime_type' => $movefile['type'], 'guid' => $movefile['url']], ['ID' => $attachment_id] ); update_attached_file($attachment_id, $new_file); $attach_data = wp_generate_attachment_metadata($attachment_id, $new_file); wp_update_attachment_metadata($attachment_id, $attach_data); } } } /** * Generate Meta Description */ public function generate_meta_tags() { if (is_singular()) { global $post; $desc = wp_trim_words(wp_strip_all_tags(strip_shortcodes($post->post_content)), 30, '...'); if (!empty($desc)) { echo '' . "\n"; } } elseif (is_front_page() || is_home()) { $desc = get_bloginfo('description'); if (!empty($desc)) { echo '' . "\n"; } } } /** * Add Open Graph XML NS */ public function add_og_xml_ns($output) { return $output . ' prefix="og: http://ogp.me/ns#"'; } /** * Generate Open Graph Tags */ public function generate_open_graph() { if (is_singular()) { global $post; $title = get_the_title(); $url = get_permalink(); $desc = wp_trim_words(wp_strip_all_tags(strip_shortcodes($post->post_content)), 30, '...'); $type = 'article'; $image = get_the_post_thumbnail_url($post->ID, 'large'); } else { $title = get_bloginfo('name'); $url = home_url('/'); $desc = get_bloginfo('description'); $type = 'website'; if (has_custom_logo()) { $image = wp_get_attachment_image_url(get_theme_mod('custom_logo'), 'full'); } else { $image = ''; } } echo '' . "\n"; echo '' . "\n"; echo '' . "\n"; if (!empty($desc)) { echo '' . "\n"; } if (!empty($image)) { echo '' . "\n"; } echo '' . "\n"; } /** * Register Sitemap Rewrite Rule */ public function register_sitemap_rewrite() { add_rewrite_rule('^sitemap\.xml$', 'index.php?aio_sitemap=1', 'top'); } /** * Render XML Sitemap */ public function render_sitemap() { $uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : ''; if (strpos($uri, 'sitemap.xml') !== false) { header('Content-Type: text/xml; charset=utf-8'); echo '' . "\n"; echo '' . "\n"; // Home page echo '' . esc_url(home_url('/')) . 'daily1.0' . "\n"; // Posts & Pages $query = new WP_Query([ 'post_type' => ['post', 'page'], 'post_status' => 'publish', 'posts_per_page' => 1000, 'orderby' => 'modified', 'order' => 'DESC' ]); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $modified = get_the_modified_time('c'); echo '' . esc_url(get_permalink()) . '' . esc_html($modified) . '0.8' . "\n"; } wp_reset_postdata(); } echo ''; exit; } } } // Init Module new AIO_Optimizer(); if (!function_exists('aio_generate_webp_for_attachment')) { function aio_generate_webp_for_attachment($attachment_id, $delete_original = false) { $file_path = get_attached_file($attachment_id); if (!$file_path || !file_exists($file_path)) return false; $mime_type = mime_content_type($file_path); if (!in_array($mime_type, ['image/jpeg', 'image/png'])) { return false; // Only convert JPEG and PNG } $path_info = pathinfo($file_path); $webp_path = $path_info['dirname'] . '/' . $path_info['filename'] . '.webp'; $success = false; // Try raw GD first for maximum control over alpha and truecolor (fixes blank/white image bug) if (function_exists('imagewebp')) { $image = null; if ($mime_type === 'image/jpeg' && function_exists('imagecreatefromjpeg')) { $image = @imagecreatefromjpeg($file_path); } elseif ($mime_type === 'image/png' && function_exists('imagecreatefrompng')) { $image = @imagecreatefrompng($file_path); } if ($image) { if (function_exists('imagepalettetotruecolor')) { @imagepalettetotruecolor($image); } if ($mime_type === 'image/png') { @imagealphablending($image, false); @imagesavealpha($image, true); } $success = @imagewebp($image, $webp_path, 85); @imagedestroy($image); } } // Fallback to WP Image Editor if GD failed or is missing if (!$success || !file_exists($webp_path) || filesize($webp_path) < 100) { $editor = wp_get_image_editor($file_path); if (!is_wp_error($editor)) { $editor->set_quality(85); $saved = $editor->save($webp_path, 'image/webp'); $success = !is_wp_error($saved); } } if ($success && file_exists($webp_path) && filesize($webp_path) > 100) { // Update attachment file and mime type in DB update_attached_file($attachment_id, $webp_path); global $wpdb; $wpdb->update( $wpdb->posts, ['post_mime_type' => 'image/webp'], ['ID' => $attachment_id], ['%s'], ['%d'] ); // Delete original file if option is enabled if ( $delete_original ) { wp_delete_file($file_path); } return true; } return false; } }