← Back
Editing: class-scanner.php
<?php defined( 'ABSPATH' ) || exit; class ADM_Alt_Scanner { /** * Collect all images needing alt text in a single SQL query. * No attachment_url_to_postid() loops — runs in under 1 second on any size site. * Returns the count queued. */ public static function build_queue( bool $only_missing = true ): int { global $wpdb; ADM_Alt_DB_Handler::clear_queue(); $mime_types = "'image/jpeg','image/jpg','image/png','image/webp','image/gif'"; if ( $only_missing ) { // Get attachments where the alt text meta is missing OR empty $sql = " SELECT p.ID, p.guid, p.post_parent, p.post_title FROM {$wpdb->posts} p LEFT JOIN {$wpdb->postmeta} m ON p.ID = m.post_id AND m.meta_key = '_wp_attachment_image_alt' WHERE p.post_type = 'attachment' AND p.post_status = 'inherit' AND p.post_mime_type IN ($mime_types) AND ( m.meta_value IS NULL OR TRIM(m.meta_value) = '' ) "; } else { $sql = " SELECT p.ID, p.guid, p.post_parent, p.post_title FROM {$wpdb->posts} p WHERE p.post_type = 'attachment' AND p.post_status = 'inherit' AND p.post_mime_type IN ($mime_types) "; } $attachments = $wpdb->get_results( $sql, ARRAY_A ); if ( empty( $attachments ) ) { return 0; } // Batch-fetch parent post titles in one query $parent_ids = array_filter( array_unique( array_column( $attachments, 'post_parent' ) ) ); $parent_titles = []; if ( $parent_ids ) { $id_list = implode( ',', array_map( 'intval', $parent_ids ) ); $rows = $wpdb->get_results( "SELECT ID, post_title FROM {$wpdb->posts} WHERE ID IN ($id_list)", ARRAY_A ); foreach ( $rows as $row ) { $parent_titles[ $row['ID'] ] = $row['post_title']; } } // Build queue items $items = []; foreach ( $attachments as $att ) { $att_id = (int) $att['ID']; $parent_id = (int) $att['post_parent']; $title = $parent_id && isset( $parent_titles[ $parent_id ] ) ? $parent_titles[ $parent_id ] : $att['post_title']; // Use the stored file URL (guid) or wp_get_attachment_url $url = wp_get_attachment_url( $att_id ); if ( ! $url ) { continue; } // Normalise domain (handles staging → live migration) $url = self::normalise_domain( $url ); $items[] = [ 'attachment_id' => $att_id, 'image_url' => $url, 'page_title' => $title, ]; } if ( $items ) { ADM_Alt_DB_Handler::enqueue( $items ); } return count( $items ); } /** * If the stored URL's domain differs from the live site domain, * rewrite it — handles sites migrated from staging without a DB search-replace. */ public static function normalise_domain( string $url ): string { $site_host = parse_url( home_url(), PHP_URL_HOST ); $image_host = parse_url( $url, PHP_URL_HOST ); if ( ! $site_host || ! $image_host || $image_host === $site_host ) { return $url; } $site_origin = parse_url( home_url(), PHP_URL_SCHEME ) . '://' . $site_host; $image_origin = parse_url( $url, PHP_URL_SCHEME ) . '://' . $image_host; return str_replace( $image_origin, $site_origin, $url ); } }
Save File
Cancel