- This topic has 11 replies, 4 voices, and was last updated 3 years, 6 months ago by
David.
-
AuthorPosts
-
October 18, 2020 at 3:06 am #1494006
Anil
Hi
How to have alt attribute on post-image… alt is empty
October 18, 2020 at 7:22 am #1494212David
StaffCustomer SupportHi there,
silly question – have you added an Alt tag to the image?
October 18, 2020 at 9:26 am #1494483Anil
David, if there is no alt tag, can I pick post_title for alt….
October 18, 2020 at 12:26 pm #1494701Tom
Lead DeveloperLead DeveloperYou 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.
October 19, 2020 at 5:08 am #1495358Anil
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; } );October 19, 2020 at 9:44 am #1495867Tom
Lead DeveloperLead DeveloperGlad it worked! 🙂
October 24, 2022 at 6:55 am #2384108James
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!
October 24, 2022 at 7:33 am #2384144David
StaffCustomer SupportHi there,
your error points to
Undefined variable $post_id– and that snippet isn’t using the$post_idvariable.
Do you have any other snippets ?October 24, 2022 at 7:43 am #2384155James
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!
October 24, 2022 at 8:03 am #2384384David
StaffCustomer SupportOh 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; } );October 24, 2022 at 8:09 am #2384399James
Aha – brilliant!
Thanks 🙂
October 24, 2022 at 8:24 am #2384421David
StaffCustomer SupportYou’re welcome
-
AuthorPosts
- You must be logged in to reply to this topic.