$v) { $o[$k] = $v; if ($k === 'tools') { $o['images'] = __('Image SEO', 'aiot-site-audit'); $o['learn'] = __('Learn', 'aiot-site-audit'); } } return $o; }, 5); /** A light list of the images: [id, bytes, mime, has alt, parent post, width, height, file name]. Kept for ten minutes. */ function aiotsa_img_index($refresh = false) { $ix = get_transient('aiotsa_img_ix'); if (is_array($ix) && !$refresh) return $ix; $max = 5000; $ids = get_posts(['post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'fields' => 'ids', 'posts_per_page' => $max + 1, 'orderby' => 'ID', 'order' => 'DESC', 'no_found_rows' => true]); $more = count($ids) > $max; $ids = array_slice($ids, 0, $max); $rows = []; foreach (array_chunk($ids, 200) as $ch) { _prime_post_caches($ch, false, true); foreach ($ch as $id) { $p = get_post($id); if (!$p) continue; $meta = wp_get_attachment_metadata($id); $meta = is_array($meta) ? $meta : []; $file = get_attached_file($id); $size = (int) ($meta['filesize'] ?? 0); if (!$size && $file && is_readable($file)) $size = (int) filesize($file); $rows[] = [(int) $id, $size, (string) $p->post_mime_type, trim((string) get_post_meta($id, '_wp_attachment_image_alt', true)) !== '' ? 1 : 0, (int) $p->post_parent, (int) ($meta['width'] ?? 0), (int) ($meta['height'] ?? 0), $file ? wp_basename($file) : $p->post_title]; } } $ix = ['at' => time(), 'rows' => $rows, 'more' => $more]; set_transient('aiotsa_img_ix', $ix, 10 * MINUTE_IN_SECONDS); return $ix; } function aiotsa_img_filters() { return ['all' => [__('All', 'aiot-site-audit'), function () { return true; }], 'heavy' => [__('Larger than 200 KB', 'aiot-site-audit'), function ($r) { return $r[1] > 204800; }], 'oldfmt' => [__('JPG, PNG or GIF', 'aiot-site-audit'), function ($r) { return in_array($r[2], ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/tiff'], true); }], 'noalt' => [__('No alt text', 'aiot-site-audit'), function ($r) { return !$r[3]; }], 'wide' => [__('Wider than 2,560 pixels', 'aiot-site-audit'), function ($r) { return $r[5] > 2560; }], 'loose' => [__('Not attached to a post', 'aiot-site-audit'), function ($r) { return !$r[4]; }]]; } function aiotsa_kb($n) { return $n >= 1048576 ? number_format_i18n($n / 1048576, 1) . ' MB' : number_format_i18n(max(1, (int) round($n / 1024))) . ' KB'; } function aiotsa_tab_images($S) { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only list filters $f = isset($_GET['f']) ? sanitize_key(wp_unslash($_GET['f'])) : 'all'; $q = isset($_GET['q']) ? sanitize_text_field(wp_unslash($_GET['q'])) : ''; $sort = isset($_GET['sort']) ? sanitize_key(wp_unslash($_GET['sort'])) : 'size'; $pg = max(1, isset($_GET['pg']) ? absint($_GET['pg']) : 1); $refresh = !empty($_GET['refresh']); // phpcs:enable $F = aiotsa_img_filters(); if (!isset($F[$f])) $f = 'all'; if (!in_array($sort, ['size', 'name', 'new'], true)) $sort = 'size'; $ix = aiotsa_img_index($refresh); $rows = $ix['rows']; $total = count($rows); $base = admin_url('admin.php?page=aiotsa&tab=images'); echo '

' . esc_html__('Image SEO', 'aiot-site-audit') . '

' . esc_html__('Every image of your Media Library with its file size, format and alt text. Heavy images slow pages down; alt text tells search engines and screen readers what an image shows.', 'aiot-site-audit') . '

'; if (!$total) { echo '

' . esc_html__('There are no images in the Media Library yet.', 'aiot-site-audit') . '

'; return; } $cnt = []; foreach ($F as $k => [$lab, $fn]) $cnt[$k] = count(array_filter($rows, $fn)); $bytes = array_sum(array_column($rows, 1)); $save = 0; $sn = 0; foreach ($rows as $r) if ($r[1] > 20480 && in_array($r[2], ['image/jpeg', 'image/png'], true)) { $save += $r[1] * 0.25; $sn++; } echo '
' . esc_html__('Images', 'aiot-site-audit') . '' . esc_html(number_format_i18n($total)) . '' . esc_html(aiotsa_kb($bytes)) . '
' . esc_html__('Larger than 200 KB', 'aiot-site-audit') . '' . esc_html(number_format_i18n($cnt['heavy'])) . '
' . esc_html__('No alt text', 'aiot-site-audit') . '' . esc_html(number_format_i18n($cnt['noalt'])) . '
' . esc_html__('JPG, PNG or GIF', 'aiot-site-audit') . '' . esc_html(number_format_i18n($cnt['oldfmt'])) . '
'; if ($ix['more']) echo '

' . esc_html__('The Media Library has more than 5,000 images. This list shows the newest 5,000.', 'aiot-site-audit') . '

'; /* translators: 1: size such as 12 MB, 2: number of images */ if ($save > 102400) echo '

' . esc_html(sprintf(__('About %1$s could be saved if the %2$s JPG and PNG files were WebP. This is an estimate: WebP files are usually 25 to 34 percent smaller than JPG.', 'aiot-site-audit'), aiotsa_kb($save), number_format_i18n($sn))) . '

'; $url = function ($a) use ($base, $f, $q, $sort) { return add_query_arg(array_filter(array_merge(['f' => $f === 'all' ? '' : $f, 'q' => $q, 'sort' => $sort === 'size' ? '' : $sort], $a), function ($v) { return $v !== '' && $v !== null; }), $base); }; echo '
' . ($f !== 'all' ? '' : '') . ' ' . esc_html__('Read the Media Library again', 'aiot-site-audit') . ''; do_action('aiotsa_images_toolbar', $f, $q, $sort); echo '
'; echo '

'; foreach ($F as $k => [$lab]) { if ($k !== 'all' && !$cnt[$k]) continue; echo '' . esc_html($lab) . ' ' . esc_html(number_format_i18n($cnt[$k])) . ' '; } echo '

'; $list = array_values(array_filter($rows, $F[$f][1])); if ($q !== '') { $ql = strtolower($q); $list = array_values(array_filter($list, function ($r) use ($ql) { return strpos(strtolower($r[7]), $ql) !== false; })); } if ($sort === 'size') usort($list, function ($a, $b) { return $b[1] <=> $a[1]; }); elseif ($sort === 'name') usort($list, function ($a, $b) { return strcasecmp($a[7], $b[7]); }); $n = count($list); $per = 100; $pages = max(1, (int) ceil($n / $per)); $pg = min($pg, $pages); $show = array_slice($list, ($pg - 1) * $per, $per); if (!$n) { echo '

' . esc_html__('No image is in this list.', 'aiot-site-audit') . '

'; return; } $ids = array_column($show, 0); _prime_post_caches($ids, false, true); $feat = aiotsa_img_featured($ids); echo '
'; foreach ($show as $r) { [$id, $size, $mime, , $parent, $w, $h, $name] = $r; $src = wp_get_attachment_url($id); $alt = (string) get_post_meta($id, '_wp_attachment_image_alt', true); $thumb = wp_get_attachment_image($id, [64, 64], true, ['loading' => 'lazy', 'alt' => '']); echo ''; echo ''; /* translators: %s: file name of an image */ echo ''; echo ''; } echo '
' . esc_html__('Image', 'aiot-site-audit') . '' . esc_html__('Size', 'aiot-site-audit') . '' . esc_html__('Alt text', 'aiot-site-audit') . '' . esc_html__('Used on', 'aiot-site-audit') . '
' . wp_kses_post($thumb) . '' . esc_html($name) . ' ' . esc_html__('(opens in a new tab)', 'aiot-site-audit') . '
' . ($w && $h ? esc_html($w . ' × ' . $h . ' px') . ' · ' : '') . '' . esc_html__('Edit', 'aiot-site-audit') . '
' . ($size ? '' . esc_html(aiotsa_kb($size)) . '' : '' . esc_html__('size not known', 'aiot-site-audit') . '') . '
' . esc_html(strtoupper(str_replace(['image/', 'jpeg', '+xml'], ['', 'jpg', ''], $mime))) . '
'; if ($parent && ($pp = get_post($parent))) echo '' . esc_html(get_the_title($pp) !== '' ? get_the_title($pp) : '#' . $parent) . ''; else echo '' . esc_html__('Not attached to a post', 'aiot-site-audit') . ''; /* translators: %d: number of posts */ if (!empty($feat[$id])) echo '
' . esc_html(sprintf(_n('Featured image of %d post', 'Featured image of %d posts', $feat[$id], 'aiot-site-audit'), $feat[$id])) . ''; echo '
'; /* translators: 1: first row, 2: last row, 3: total */ echo '

' . esc_html(sprintf(__('Showing %1$s to %2$s of %3$s images', 'aiot-site-audit'), number_format_i18n(($pg - 1) * $per + 1), number_format_i18n(($pg - 1) * $per + count($show)), number_format_i18n($n))) . ' '; if ($pg > 1) echo '' . esc_html__('Previous 100', 'aiot-site-audit') . ' '; if ($pg < $pages) echo '' . esc_html__('Next 100', 'aiot-site-audit') . ''; echo '

'; echo '
' . esc_html__('What this page does, and its limits', 'aiot-site-audit') . '
'; } /** How many posts use each of these images as their featured image. */ function aiotsa_img_featured($ids) { global $wpdb; $ids = array_values(array_filter(array_map('absint', (array) $ids))); if (!$ids) return []; $out = []; $rows = $wpdb->get_results($wpdb->prepare('SELECT meta_value AS id, COUNT(*) AS n FROM %i WHERE meta_key = %s AND meta_value IN (' . implode(',', array_fill(0, count($ids), '%s')) . ') GROUP BY meta_value', array_merge([$wpdb->postmeta, '_thumbnail_id'], array_map('strval', $ids)))); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders foreach ((array) $rows as $r) $out[(int) $r->id] = (int) $r->n; return $out; } add_action('rest_api_init', function () { register_rest_route('aiotsa/v1', '/images/alt', ['methods' => 'POST', 'permission_callback' => function () { return current_user_can('manage_options'); }, 'callback' => function ($q) { $id = absint($q['id']); $p = $id ? get_post($id) : null; if (!$p || $p->post_type !== 'attachment' || strpos((string) $p->post_mime_type, 'image/') !== 0 || !current_user_can('edit_post', $id)) return new WP_REST_Response(['error' => __('This image cannot be changed.', 'aiot-site-audit')], 400); $alt = mb_substr(sanitize_text_field((string) $q['alt']), 0, 250); update_post_meta($id, '_wp_attachment_image_alt', $alt); $ix = get_transient('aiotsa_img_ix'); if (is_array($ix)) { foreach ($ix['rows'] as &$r) if ($r[0] === $id) { $r[3] = $alt !== '' ? 1 : 0; break; } unset($r); set_transient('aiotsa_img_ix', $ix, 10 * MINUTE_IN_SECONDS); } return ['ok' => true, 'alt' => $alt]; }]); }); /* ---------- Tools: page address ideas ---------- */ function aiotsa_slug_stop() { return array_flip(['a', 'an', 'the', 'and', 'or', 'but', 'of', 'to', 'in', 'on', 'for', 'with', 'at', 'by', 'from', 'is', 'are', 'was', 'be', 'this', 'that', 'your', 'you', 'my', 'our', 'how', 'what', 'why']); } /** What is weak about a slug. */ function aiotsa_slug_issues($slug) { $is = []; $s = (string) $slug; $w = array_values(array_filter(explode('-', $s), 'strlen')); if (strlen($s) > 60 || count($w) > 8) $is[] = __('long', 'aiot-site-audit'); if (preg_match('/^\d+$/', $s) || preg_match('/^(post|page|untitled|draft|new-post|sample-page|hello-world)(-\d+)?$/i', $s)) $is[] = __('says nothing', 'aiot-site-audit'); elseif (preg_match('/-\d$/', $s) && !preg_match('/-\d{4}$/', $s)) $is[] = __('ends in a number', 'aiot-site-audit'); if (preg_match('/[_%]|[A-Z]/', $s)) $is[] = __('odd characters', 'aiot-site-audit'); return $is; } /** A shorter slug from the title: main words only, at most six. */ function aiotsa_slug_suggest($title) { $t = preg_split('/\s+[\-–—|:]\s+/u', wp_strip_all_tags((string) $title))[0]; $w = array_values(array_filter(explode('-', sanitize_title($t)), 'strlen')); $stop = aiotsa_slug_stop(); $keep = array_values(array_filter($w, function ($x) use ($stop) { return !isset($stop[$x]); })); if (count($keep) < 2) $keep = $w; return implode('-', array_slice($keep, 0, 6)); } add_action('aiotsa_tools_panels', function ($S) { echo '

' . esc_html__('Page address ideas', 'aiot-site-audit') . '

' . esc_html__('Published posts and pages whose address (slug) is long, ends in a number or says nothing, with a shorter idea made from the title.', 'aiot-site-audit') . '

'; $ids = get_posts(['post_type' => ['post', 'page'], 'post_status' => 'publish', 'fields' => 'ids', 'posts_per_page' => 500, 'orderby' => 'modified', 'order' => 'DESC', 'no_found_rows' => true]); $rows = []; $front = (int) get_option('page_on_front'); foreach ($ids as $id) { if ($id === $front) continue; $p = get_post($id); $is = aiotsa_slug_issues($p->post_name); if (!$is) continue; $new = aiotsa_slug_suggest($p->post_title); if ($new === '' || $new === $p->post_name) continue; $rows[] = [$p, $is, $new]; if (count($rows) >= 100) break; } if (!$rows) { echo '

' . esc_html__('The addresses of your newest 500 posts and pages look fine.', 'aiot-site-audit') . '

'; return; } echo '
'; foreach ($rows as [$p, $is, $new]) { $old = (string) wp_parse_url(get_permalink($p), PHP_URL_PATH); $np = preg_replace('#' . preg_quote($p->post_name, '#') . '(/?)$#', $new . '$1', $old); echo ''; } echo '
' . esc_html__('Post or page', 'aiot-site-audit') . '' . esc_html__('Address now', 'aiot-site-audit') . '' . esc_html__('Idea', 'aiot-site-audit') . '' . esc_html__('Redirect line (Apache)', 'aiot-site-audit') . '
' . esc_html(get_the_title($p)) . '' . esc_html($p->post_name) . '
' . esc_html(implode(', ', $is)) . '
' . esc_html($new) . '' . esc_html('Redirect 301 ' . $old . ' ' . $np) . '
' . esc_html__('Before you change an address', 'aiot-site-audit') . '
'; });