This PHP script is designed to automatically assign alt text to images in WordPress posts if they are missing it. The alt text is generated based on the post's title followed by an image counter. This ensures that all images have meaningful alt text, which is beneficial for SEO and accessibility.
Function: auto_assign_alt_text_to_images
Purpose
The function
auto_assign_alt_text_to_images processes the content of a WordPress post, identifies images without alt text, and assigns them alt text derived from the post's title.
Parameters
$content (string): The content of the WordPress post.
Returns
- (string): The modified content with updated alt text for images.
Logic
- Check if the post is a single post and has a featured image:
if (is_single() && has_post_thumbnail($post->ID)) {
- Sanitize the post title:
$post_title = sanitize_text_field($post->post_title);
- Load the post content into a DOMDocument object:
$doc = new DOMDocument();
@$doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
- Get all images in the post:
$images = $doc->getElementsByTagName('img');
- Initialize an image counter:
- Loop through each image and assign alt text if missing:
foreach ($images as $img) {
$alt = $img->getAttribute('alt');
if (empty($alt)) {
$new_alt = $post_title . ' Image ' . $image_counter;
$img->setAttribute('alt', $new_alt);
$image_counter++;
}
}
- Save the modified content back to the
$content variable:
$content = $doc->saveHTML();
- Return the modified content:
Hook: add_filter
The function
auto_assign_alt_text_to_images is hooked into the
the_content filter, ensuring it runs whenever the post content is processed.
add_filter('the_content', 'auto_assign_alt_text_to_images');
Example
Before:
<img src="example.jpg" alt="">
<img src="example2.jpg" alt="Already has alt text">
<img src="example3.jpg" alt="">
After:
<img src="example.jpg" alt="Post Title Image 1">
<img src="example2.jpg" alt="Already has alt text">
<img src="example3.jpg" alt="Post Title Image 2">
In this example, the post title is "Post Title". The script adds "Post Title Image 1" and "Post Title Image 2" as alt text for the first and third images, respectively.