Skip to content

Commit

Permalink
Fix not auto generating alt text for existing images
Browse files Browse the repository at this point in the history
  • Loading branch information
rilwis committed Oct 18, 2023
1 parent 5fe8b39 commit 9281908
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions src/ImagesAlt.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,33 @@

class ImagesAlt {
public function setup() {
// Add missing alt attribute when outputting images via the_post_thumbnail-family functions.
add_filter( 'wp_get_attachment_image_attributes', [ $this, 'add_missing_alt_attribute' ], 10, 2 );

// Add missing alt attribute when inserting images to the editor. Work with both classic and Gutenberg editor.
add_filter( 'wp_prepare_attachment_for_js', [ $this, 'add_missing_alt_attribute' ], 10, 2 );

add_action( 'add_attachment', [ $this, 'generate_alt_text_on_upload' ] );

// Fix missing alt text for avatar.
add_filter( 'get_avatar', [ $this, 'add_avatar_alt' ], 10, 5 );
}

public function add_missing_alt_attribute( array $attributes, WP_Post $attachment ): array {
$attributes['alt'] = $attributes['alt'] ?: $this->normalize( $attachment->post_title );
return $attributes;
}

public function generate_alt_text_on_upload( int $post_id ): void {
if ( ! wp_attachment_is_image( $post_id ) ) {
return;
}

$title = get_post( $post_id )->post_title;

// Sanitize the title: remove hyphens, underscores & extra spaces.
$title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $title );

// Sanitize the title: capitalize first letter of every word (other letters lower case).
$title = ucwords( strtolower( $title ) );
$alt = get_post( $post_id )->post_title;
$alt = $this->normalize( $alt );

// Set the image alt-text.
update_post_meta( $post_id, '_wp_attachment_image_alt', $title );
update_post_meta( $post_id, '_wp_attachment_image_alt', $alt );
}

public function add_avatar_alt( string $avatar, $id_or_email, int $size, string $default_value, string $alt ): string {
Expand Down Expand Up @@ -69,4 +75,14 @@ private function get_alt_from_id_or_email( $id_or_email ): string {

return $user instanceof WP_User ? $user->display_name : $email;
}

private function normalize( string $alt ): string {
// Remove hyphens, underscores & extra spaces.
$alt = preg_replace( '%\s*[-_\s]+\s*%', ' ', $alt );

// Capitalize first letter of every word (other letters lower case).
$alt = ucwords( strtolower( $alt ) );

return $alt;
}
}

0 comments on commit 9281908

Please sign in to comment.