*/ public static function defaults(): array { return array( 'auto_alt' => true, 'auto_title' => false, 'auto_caption' => false, 'alt_template' => '%filename%', 'title_template' => '%title%', 'caption_template' => '', 'link_nofollow' => false, 'link_new_tab' => false, 'link_exclude' => '', ); } public function register( Container $container ): void {} public function boot( Container $container ): void { add_action( 'rest_api_init', array( $this, 'routes' ) ); $settings = $this->settings(); if ( ! empty( $settings['auto_alt'] ) || ! empty( $settings['auto_title'] ) ) { add_filter( 'wp_get_attachment_image_attributes', array( $this, 'image_attributes' ), 10, 2 ); add_action( 'add_attachment', array( $this, 'fill_on_upload' ) ); } if ( ! empty( $settings['link_nofollow'] ) || ! empty( $settings['link_new_tab'] ) ) { Guard::filter( 'the_content', array( $this, 'external_links' ), 20 ); } } /** * Fill missing alt/title when an image is rendered. * * @param array $attr Image attributes. * @param \WP_Post $attachment The attachment. * @return array */ public function image_attributes( array $attr, $attachment ): array { if ( ! $attachment instanceof \WP_Post ) { return $attr; } $settings = $this->settings(); if ( ! empty( $settings['auto_alt'] ) && empty( trim( (string) ( $attr['alt'] ?? '' ) ) ) ) { $alt = $this->build_text( $attachment, (string) $settings['alt_template'] ); // The template can legitimately come out empty — "%filename%" on a // file called DSC_0001 is nothing worth saying. Rather than leave // the attribute blank, fall through to what the site does know // about the image. $attr['alt'] = '' !== $alt ? $alt : $this->fallback_text( $attachment ); } if ( ! empty( $settings['auto_title'] ) && empty( $attr['title'] ) ) { $attr['title'] = $this->build_text( $attachment, (string) ( $settings['title_template'] ?? '%title%' ) ); } // An empty value is worse than no attribute: a screen reader announces // "image" either way, and an empty alt tells it the image is decorative. foreach ( array( 'alt', 'title' ) as $key ) { if ( isset( $attr[ $key ] ) && '' === trim( (string) $attr[ $key ] ) && 'alt' !== $key ) { unset( $attr[ $key ] ); } } return $attr; } /** * Store alt text at upload time so it is also present in the media library. * * @param int $attachment_id Attachment ID. */ public function fill_on_upload( int $attachment_id ): void { if ( ! wp_attachment_is_image( $attachment_id ) ) { return; } if ( '' !== trim( (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ) { return; } $attachment = get_post( $attachment_id ); if ( ! $attachment instanceof \WP_Post ) { return; } $alt = $this->build_text( $attachment, (string) $this->settings()['alt_template'] ); if ( '' !== $alt ) { update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt ); } } /** * Resolve the alt/title template for an attachment. */ /** * What to say about an image when the template said nothing: the caption, * then the image's own title if it is not camera noise, then the page the * image sits on. Failing all three, nothing — an invented alt is worse * than an honest gap, and a screen reader treats an empty alt as * "decorative", which is the correct reading of an image nobody described. */ private function fallback_text( \WP_Post $attachment ): string { $caption = trim( wp_strip_all_tags( (string) $attachment->post_excerpt ) ); if ( '' !== $caption ) { return $caption; } $title = trim( wp_strip_all_tags( get_the_title( $attachment ) ) ); if ( '' !== $title && '' !== self::clean_filename( $title ) ) { return $title; } return $attachment->post_parent ? trim( wp_strip_all_tags( (string) get_the_title( (int) $attachment->post_parent ) ) ) : ''; } /** * The variables a template may use, with a label. One list, used by the * resolver and by the settings screen, so the hint cannot promise a * variable the resolver drops. * * @return array */ public static function variables(): array { return array( '%filename%' => __( 'File name, cleaned up', 'ai-rank-suite' ), '%title%' => __( 'Image title', 'ai-rank-suite' ), '%caption%' => __( 'Caption', 'ai-rank-suite' ), '%postname%' => __( 'Title of the page the image sits on', 'ai-rank-suite' ), '%category%' => __( 'That page’s first category', 'ai-rank-suite' ), '%sitename%' => __( 'Site name', 'ai-rank-suite' ), '%currentyear%' => __( 'Current year', 'ai-rank-suite' ), '%index%' => __( 'Position of the image on the page', 'ai-rank-suite' ), ); } /** * A file name worth showing, or nothing. * * On a real site a file name is "IMG_4821", "DSC 0001", "photo-3-scaled" * or "shutterstock_1929384756-1024x768" — text that helps no reader and * reads to a search engine as a field filled by a machine. What is left * after the camera prefixes, the size suffixes, the stock-library ids and * the bare numbers is either a real description or nothing at all, and * nothing is the honest answer. */ public static function clean_filename( string $file ): string { $name = (string) pathinfo( $file, PATHINFO_FILENAME ); $name = (string) preg_replace( '/-\d+x\d+$/', '', $name ); // WordPress size suffix. $name = (string) preg_replace( '/[-_]?scaled$/i', '', $name ); // WordPress "scaled" original. $name = (string) preg_replace( '/[-_]?(e\d{10,}|\d{10,})$/', '', $name ); // Edited-copy timestamps. $name = (string) preg_replace( '/[-_]+/', ' ', $name ); // Camera and stock-library prefixes, and the bare numbers beside them. $name = (string) preg_replace( '/\b(img|dsc|dscn|dscf|pxl|mvimg|photo|image|foto|bild|screenshot|shutterstock|istock|adobestock|depositphotos|pexels|unsplash|copy|final|v\d+)\b/i', ' ', $name ); $name = (string) preg_replace( '/\b\d{2,}\b/', ' ', $name ); $name = trim( (string) preg_replace( '/\s{2,}/', ' ', $name ) ); // One or two stray characters are not a description either. return mb_strlen( $name ) < 3 ? '' : ucfirst( $name ); } /** * Fill a template for one attachment. A variable nothing can fill is * dropped rather than printed — "%category%" in an alt attribute is worse * than a shorter sentence. */ /** * The media library, counted. * * Every image attachment: how many have no alt text, how many are wider * than 2500 pixels, how many weigh more than half a megabyte. The * dimensions and the weight live in the serialized attachment metadata, * so they are read per image and the result is cached ten minutes; a * library past five thousand images is sampled to its newest five * thousand and says so. * * @return array */ public function audit( bool $fresh = false ): array { $key = 'airanksuite_image_audit'; if ( ! $fresh ) { $cached = get_transient( $key ); if ( is_array( $cached ) ) { return $cached; } } global $wpdb; $cap = 5000; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE post_type = 'attachment' AND post_mime_type LIKE %s", $wpdb->posts, 'image/%' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $no_alt = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i p LEFT JOIN %i m ON m.post_id = p.ID AND m.meta_key = '_wp_attachment_image_alt' WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE %s AND ( m.meta_value IS NULL OR m.meta_value = '' )", $wpdb->posts, $wpdb->postmeta, 'image/%' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $rows = $wpdb->get_results( $wpdb->prepare( "SELECT p.ID, p.post_title, m.meta_value FROM %i p INNER JOIN %i m ON m.post_id = p.ID AND m.meta_key = '_wp_attachment_metadata' WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE %s ORDER BY p.ID DESC LIMIT %d", $wpdb->posts, $wpdb->postmeta, 'image/%', $cap ), ARRAY_A ); $oversized = array(); $heavy = 0; foreach ( (array) $rows as $row ) { $meta = maybe_unserialize( (string) $row['meta_value'] ); if ( ! is_array( $meta ) ) { continue; } $w = (int) ( $meta['width'] ?? 0 ); $h = (int) ( $meta['height'] ?? 0 ); $b = (int) ( $meta['filesize'] ?? 0 ); if ( $b > 512 * 1024 ) { ++$heavy; } if ( $w > 2500 ) { $oversized[] = array( 'id' => (int) $row['ID'], 'title' => (string) $row['post_title'], 'width' => $w, 'height' => $h, 'bytes' => $b, 'edit' => (string) get_edit_post_link( (int) $row['ID'], 'raw' ), ); } } usort( $oversized, static fn( $a, $b ) => $b['width'] <=> $a['width'] ); $out = array( 'total' => $total, 'no_alt' => $no_alt, 'oversized' => count( $oversized ), 'heavy' => $heavy, 'sampled' => $total > $cap, 'largest' => array_slice( $oversized, 0, 15 ), 'template' => (string) $this->settings()['alt_template'], ); set_transient( $key, $out, 10 * MINUTE_IN_SECONDS ); return $out; } /** * Fill the alt text of every image that has none, from the template, * fifty images per call. The browser calls again until `done` is true. * * @return array */ public function fill( int $offset ): array { global $wpdb; $template = (string) $this->settings()['alt_template']; $slice = 50; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $ids = $wpdb->get_col( $wpdb->prepare( "SELECT p.ID FROM %i p LEFT JOIN %i m ON m.post_id = p.ID AND m.meta_key = '_wp_attachment_image_alt' WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE %s AND ( m.meta_value IS NULL OR m.meta_value = '' ) ORDER BY p.ID ASC LIMIT %d OFFSET %d", $wpdb->posts, $wpdb->postmeta, 'image/%', $slice, $offset ) ); $filled = 0; $skipped = 0; foreach ( (array) $ids as $id ) { $attachment = get_post( (int) $id ); if ( ! $attachment instanceof \WP_Post ) { continue; } $alt = $this->build_text( $attachment, $template ); if ( '' === $alt ) { $alt = $this->fallback_text( $attachment ); } if ( '' === $alt ) { ++$skipped; continue; } update_post_meta( (int) $id, '_wp_attachment_image_alt', $alt ); ++$filled; } delete_transient( 'airanksuite_image_audit' ); // Filled images leave the "without alt" set, so the offset only has to // step past the ones that were skipped. return array( 'filled' => $filled, 'skipped' => $skipped, 'offset' => $offset + $skipped, 'done' => count( (array) $ids ) < $slice, ); } private function build_text( \WP_Post $attachment, string $template, int $index = 0 ): string { if ( '' === trim( $template ) ) { return ''; } $parent = $attachment->post_parent ? (int) $attachment->post_parent : 0; $category = ''; if ( $parent > 0 ) { $terms = get_the_terms( $parent, 'category' ); if ( is_array( $terms ) && ! empty( $terms ) ) { $category = (string) $terms[0]->name; } } $value = strtr( $template, array( '%filename%' => self::clean_filename( (string) get_post_meta( $attachment->ID, '_wp_attached_file', true ) ), '%title%' => wp_strip_all_tags( get_the_title( $attachment ) ), '%caption%' => wp_strip_all_tags( (string) $attachment->post_excerpt ), '%postname%' => $parent > 0 ? wp_strip_all_tags( (string) get_the_title( $parent ) ) : '', '%category%' => $category, '%sitename%' => (string) get_bloginfo( 'name' ), '%currentyear%' => (string) wp_date( 'Y' ), '%index%' => $index > 0 ? (string) $index : '', ) ); // Whatever is still in variable shape means nothing here. $value = (string) preg_replace( '/%[a-z_0-9]+%/i', '', $value ); // And the punctuation the dropped variable was holding up. $value = (string) preg_replace( '/\(\s*[,;–-]*\s*\)/', '', $value ); $value = trim( (string) preg_replace( '/\s{2,}/', ' ', $value ) ); return trim( $value, " \t\n\r\0\x0B-–—,;:|" ); } /** * Add rel/target attributes to external links in post content. */ public function external_links( string $content ): string { if ( is_admin() || is_feed() ) { return $content; } $settings = $this->settings(); $home = (string) wp_parse_url( home_url(), PHP_URL_HOST ); $exclude = array_filter( array_map( 'trim', explode( "\n", (string) $settings['link_exclude'] ) ) ); return (string) preg_replace_callback( '/]*href=["\']([^"\']+)["\'][^>]*)>/i', static function ( array $m ) use ( $settings, $home, $exclude ): string { $attrs = $m[1]; $href = $m[2]; $host = (string) wp_parse_url( $href, PHP_URL_HOST ); if ( '' === $host || $host === $home ) { return $m[0]; } foreach ( $exclude as $domain ) { if ( '' !== $domain && str_contains( $host, $domain ) ) { return $m[0]; } } if ( ! empty( $settings['link_nofollow'] ) && ! preg_match( '/\brel=/i', $attrs ) ) { $attrs .= ' rel="nofollow noopener"'; } if ( ! empty( $settings['link_new_tab'] ) && ! preg_match( '/\btarget=/i', $attrs ) ) { $attrs .= ' target="_blank"'; if ( ! preg_match( '/\brel=/i', $attrs ) ) { $attrs .= ' rel="noopener"'; } } return ''; }, $content ); } public function routes(): void { // The media library, counted: how many images say nothing, how many // are too big, and a way to fill the alt texts in one run. register_rest_route( self::NAMESPACE, '/image-seo/audit', array( 'methods' => 'GET', 'callback' => fn( WP_REST_Request $request ) => new WP_REST_Response( $this->audit( (bool) $request->get_param( 'fresh' ) ) ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'fresh' => array( 'type' => 'boolean', 'default' => false ) ), ) ); register_rest_route( self::NAMESPACE, '/image-seo/fill', array( 'methods' => 'POST', 'callback' => fn( WP_REST_Request $request ) => new WP_REST_Response( $this->fill( (int) $request->get_param( 'offset' ) ) ), 'permission_callback' => static function () { if ( ! current_user_can( 'manage_options' ) ) { return self::forbidden(); } return self::spend( 'image_fill', 200 ); }, 'args' => array( 'offset' => array( 'type' => 'integer', 'default' => 0, 'minimum' => 0 ) ), ) ); register_rest_route( self::NAMESPACE, '/settings/image-seo', array( array( 'methods' => 'GET', 'callback' => fn() => new WP_REST_Response( array( 'settings' => $this->settings(), 'variables' => self::variables() ) ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ), array( 'methods' => 'PUT', 'callback' => array( $this, 'update_settings' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'auto_alt' => array( 'type' => 'boolean' ), 'auto_title' => array( 'type' => 'boolean' ), 'alt_template' => array( 'type' => 'string', // The UI offers %caption% as a clickable chip and // sanitize_text_field strips it to "ption%" — worse than // failing, because the other four tokens survive and it // looks like it worked. 'sanitize_callback' => array( \AiRankSuite\Support\Sanitize::class, 'template' ), ), 'auto_caption' => array( 'type' => 'boolean' ), 'title_template' => array( 'type' => 'string', 'sanitize_callback' => array( \AiRankSuite\Support\Sanitize::class, 'template' ), ), 'caption_template' => array( 'type' => 'string', 'sanitize_callback' => array( \AiRankSuite\Support\Sanitize::class, 'template' ), ), 'link_nofollow' => array( 'type' => 'boolean' ), 'link_new_tab' => array( 'type' => 'boolean' ), 'link_exclude' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', ), ), ), ) ); } public function update_settings( WP_REST_Request $request ): WP_REST_Response { $defaults = self::defaults(); $values = array(); foreach ( array_keys( $defaults ) as $key ) { if ( $request->has_param( $key ) ) { $values[ $key ] = $request->get_param( $key ); } } \AiRankSuite\Kernel::service( Options::class )->set( 'image_seo', $values, $defaults ); return new WP_REST_Response( array( 'settings' => $this->settings() ) ); } /** @return array */ private function settings(): array { return \AiRankSuite\Kernel::service( Options::class )->get( 'image_seo', self::defaults() ); } }