Image Alt Text based on Post Title

Hello,

with the following Code Snippet you can update all your Images Alt Texts by clicking save on your posts.

This works by adding the Post Title as the Image Alt Text when you save a post. This works on all already existing images and posts; you’ll need to update them/save them again, for the Alt Text to apply.

  • Only updates images without Alt Text
  • Uses the Post Title, where the image is placed, as Alt Text
  • Updates on Save
  • Ignores all media files with existing Alt Texts
/**
 * Set post title as alt text for images used in posts when:
 * 1) No alt text exists
 * 2) Image appears in post content or as featured image
 */
add_filter('wp_get_attachment_image_attributes', 'dynamic_alt_text_based_on_usage', 10, 3);
add_action('save_post', 'update_image_alt_on_post_save', 10, 3);

// Dynamic alt text for frontend display
function dynamic_alt_text_based_on_usage($attributes, $attachment, $size) {
    global $post;
    
    if (!empty($attributes['alt'])) return $attributes;
    if (!$post) return $attributes;

    // Check featured image
    $featured_image_id = get_post_thumbnail_id($post->ID);
    if ($featured_image_id == $attachment->ID) {
        $attributes['alt'] = esc_attr(get_the_title($post->ID));
        return $attributes;
    }

    // Check content images
    if (strpos($post->post_content, 'wp-image-' . $attachment->ID) !== false) {
        $attributes['alt'] = esc_attr(get_the_title($post->ID));
    }

    return $attributes;
}

// Permanent alt text update when saving posts
function update_image_alt_on_post_save($post_id, $post, $update) {
    if (!current_user_can('edit_post', $post_id) || wp_is_post_autosave($post_id)) return;

    $image_ids = [];
    
    // Get featured image
    if ($featured_id = get_post_thumbnail_id($post_id)) {
        $image_ids[] = $featured_id;
    }

    // Get images from content
    preg_match_all('/wp-image-(\d+)/', $post->post_content, $matches);
    if (!empty($matches[1])) {
        $image_ids = array_merge($image_ids, $matches[1]);
    }

    // Update alt texts
    foreach (array_unique($image_ids) as $image_id) {
        $current_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
        if (empty($current_alt)) {
            update_post_meta(
                $image_id,
                '_wp_attachment_image_alt',
                sanitize_text_field(get_the_title($post_id))
            );
        }
    }
}

Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *