Archived topic
alt attribute on post-image
11 replies · Started by Anil on October 18, 2020
Hi
How to have alt attribute on post-image... alt is empty
Hi there,
silly question - have you added an Alt tag to the image?
David, if there is no alt tag, can I pick post_title for alt....
You could try this:
add_filter( 'wp_get_attachment_image_attributes', function( $atts ) {
if ( empty( $atts['alt'] ) ) {
$atts['alt'] = the_title_attribute( 'echo=0' ),
}
return $atts;
} );
Not sure if it will work or not, but worth a shot.
Thanks Tom, following code working, now it does not show empty alt"", it takes aticle's title as alt attribute. It is helpful in a big and old website, where you do not have mentioned alt while uploading images ... (this can be included in GP as well; rather showing empty alt"")
Regards.
add_filter( 'wp_get_attachment_image_attributes', function( $atts ) {
if ( empty( $atts['alt'] ) ) {
$atts['alt'] = the_title_attribute( 'echo=0' );
}
return $atts;
} );
Glad it worked! :)
Hi! This code works great.
However, when putting a site on PHP8 (from 7.4) it's giving this error in the PHP error log:
PHP Warning: Undefined variable $post_id in /home/username/public_html/wp-content/plugins/code-snippets/php/snippet-ops.php(505) : eval()'d code on line 2
Is there a tweak that can be done to make it play nicely with PHP8?
Thanks!
Hi there,
your error points to Undefined variable $post_id - and that snippet isn't using the $post_id variable.
Do you have any other snippets ?
Ah, sorry David. Me being a twit on a Monday morning...
The snippet I've got (to put the post title as featured image alts) is:
add_filter( 'wp_get_attachment_image_attributes', function( $atts ) {
if ( get_post_type( $post_id ) === 'post' ) {
$atts['alt'] = the_title_attribute( 'echo=0' );
}
return $atts;
} );
I was sure I got it from here - but apparently not!
Oh no worries, my brain is super foggy today lol
Try:
add_filter( 'wp_get_attachment_image_attributes', function( $atts ) {
if ( get_post_type( get_the_ID() ) === 'post' ) {
$atts['alt'] = the_title_attribute( 'echo=0' );
}
return $atts;
} );
Aha - brilliant!
Thanks :)
You're welcome