• Custom Plugin
  • |
  • PHP
  • |
  • WordPress
  • |
  • WPCodebox

Automatically Assign ALT Text to Images in WordPress Posts If They are Missing

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

  1. Check if the post is a single post and has a featured image:
    if (is_single() && has_post_thumbnail($post->ID)) {
  2. Sanitize the post title:
    $post_title = sanitize_text_field($post->post_title);
  3. Load the post content into a DOMDocument object:
    $doc = new DOMDocument();
    @$doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
  4. Get all images in the post:
    $images = $doc->getElementsByTagName('img');
  5. Initialize an image counter:
    $image_counter = 1;
  6. 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++;
    }
    }
  7. Save the modified content back to the $content variable:
    $content = $doc->saveHTML();
  8. Return the modified content:
    return $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.


Usage

To use this function in your WordPress theme or plugin, simply add a PHP snippet in WPCODEBOX plugin.

Instructions:

  1. Add a PHP snippet in WPCodebox
  2. Paste the code from below
  3. Save it once
  4. Enable it and save it again

Or you can add this code to your functions.php file or the relevant plugin file.

This will ensure that any single post with a featured image will automatically have alt text assigned to any images that are missing it.

Type: PHP

function auto_assign_alt_text_to_images($content) {
    global $post;
    if (is_single() && has_post_thumbnail($post->ID)) {
        $post_title = sanitize_text_field($post->post_title);
        $doc = new DOMDocument();
        @$doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
        $images = $doc->getElementsByTagName('img');
        $image_counter = 1;

        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++;
            }
        }

        $content = $doc->saveHTML();
    }
    return $content;
}

add_filter('the_content', 'auto_assign_alt_text_to_images');


More Codes

Automatic Table of Content for Your WordPress Posts, Conditional Auto Insert before the First H2

Enhance long-form content readability with WPCodeBox’s Automatic Table of Contents before the first H2 header. Try it now and improve user experience!

Automatically Assign ALT Text to Images in WordPress Posts If They are Missing

Automatically assign ALT text to images in WordPress posts with WPCodeBox. Improve SEO and accessibility easily with this PHP script!

Shell/Bash Script Migrating WordPress – Find and Replace all Instance of Domain Name in WordPress or MySQL Database

Automate WordPress Domain Migration with our Shell Script. Easily Find & Replace all instances of your old domain in the MySQL database. Try it now!