Skip to content

Instantly share code, notes, and snippets.

@sagarjadhav
Created October 12, 2021 12:07
Show Gist options
  • Save sagarjadhav/3a9f0866df67ffe3298db0b7deee2e5f to your computer and use it in GitHub Desktop.
Save sagarjadhav/3a9f0866df67ffe3298db0b7deee2e5f to your computer and use it in GitHub Desktop.
Filter attachment image attributes to inject alt attribute to Image
<?php
if ( ! function_exists( 'rtcamp_add_img_alt_attribute' ) ) {
/**
* Filter attachment image attributes to inject alt attribute.
*
* @param string[] $attrs Array of attribute values for the image markup, keyed by attribute name.
* @param WP_Post|null $attachment Image attachment post.
* @return string[] Filtered attributes.
*/
function rtcamp_add_img_alt_attribute( $attrs, $attachment = null ) {
if ( empty( $attrs['alt'] ) ) {
$img_title = trim( wp_strip_all_tags( $attachment->post_title ) );
$attrs['alt'] = $img_title;
$attrs['title'] = $img_title;
}
return $attrs;
}
add_filter( 'wp_get_attachment_image_attributes', 'rtcamp_add_img_alt_attribute', 10, 2 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment