Created
October 12, 2021 12:07
-
-
Save sagarjadhav/3a9f0866df67ffe3298db0b7deee2e5f to your computer and use it in GitHub Desktop.
Filter attachment image attributes to inject alt attribute to Image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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