Skip to content

Instantly share code, notes, and snippets.

@dmje
Created August 14, 2025 09:14
Show Gist options
  • Save dmje/cf38a3971d2960385b17682253ffd6e4 to your computer and use it in GitHub Desktop.
Save dmje/cf38a3971d2960385b17682253ffd6e4 to your computer and use it in GitHub Desktop.
The problem: if you add ALT tags after adding images to a page, WordPress doesn't by default use these (WTF!) - add this to functions to sort...
<?php
// Sorting out image ALTs
// from https://www.billerickson.net/code/wordpress-image-automatic-alt-text/
add_filter('render_block',
function ($content, $block) {
if ('core/image' !== $block['blockName']) {
return $content;
}
if (isset($block) && isset($block['attrs']) && isset($block['attrs']['id'])) {
$alt = get_post_meta($block['attrs']['id'], '_wp_attachment_image_alt', true);
} else {
$alt = '';
}
if (empty($alt)) {
return $content;
}
// Empty alt
if (false !== strpos($content, 'alt=""')) {
$content = str_replace('alt=""', 'alt="' . $alt . '"', $content);
// No alt
} elseif (false === strpos($content, 'alt="')) {
$content = str_replace('src="', 'alt="' . $alt . '" src="', $content);
}
return $content;
},
10,
2
);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment