Archived topic
Add custom image class to featured images
12 replies · Started by forgemedia on June 19, 2018
Is there an easy way to add a custom class to featured images on blog posts? For example, take my post here: https://woorkup.com/happyforms-vs-contact-form-7/
Currently, it looks like this:
<img width="1588" height="796" src="https://woorkup.com/wp-content/uploads/2018/05/contact-form-7-vs-happyforms-1.png"......
I would like it to look like this:
<img width="1588" height="796" class="mycustomclass" src="https://woorkup.com/wp-content/uploads/2018/05/contact-form-7-vs-happyforms-1.png"......
I am using the Code Snippets plugin :) Perhaps some quick PHP?
Thanks!
Nevermind... realized there was a "attachment-full size-full" further down I could target :)
I'm all good!
Glad you found a solution :)
You can always do this as well:
.featured-image img
I would love a way to actually do this (to add a class not just select it for JS/CSS purposes)
Are you referring to the featured image on the posts page or single posts?
Hey Leo, on the single posts page
Doesn't look like there is a filter there unfortunately.
What are you trying to achieve?
Just wondering if there is a workaround.
I want to add either a class or data attribute to the feature image (so I can exclude the image from being lazy loaded in A3 lazy load)
Hi there,
You could try this:
add_filter( 'wp_get_attachment_image_attributes', function( $attrs ) {
if ( is_single() ) {
$attrs['data-something'] = 'my-value';
}
return $attrs;
} );
Hello to all,
sorry to wake this old Post, but I didn't want to open up a new one. I am looking for the exact same function, but I am not able to do it correctly.
I tried this code:
function wpzeus_filter_gallery_img_atts( $atts, $attachment ) {
global $post;
if ( is_single() && (isset($atts['class'])) && (($attachment->post_parent) === ($post->ID)) ) {
$atts['id'] = 'mycostumid';
}
return $atts;
}
add_filter( 'wp_get_attachment_image_attributes', 'wpzeus_filter_gallery_img_atts', 10, 2 );
The problem is the following: I am using wp show posts (pro) to display some posts in my sidebar. This function is applying the mycustomid to all the posts shown by wp show posts AND the featured image.
-> Since I need the id to exclude only the featured image, it would be kind of ineffective
I already tried to filter it by logical operators, but I couldn't find something.
Also I can't use the selector (.featured-image img), because "rendering" it requires JS code, which doesn't make sense when looking for page speed.
Is there any solution to add a custom ID attribute ONLY to the featured image of the current single post?
Thanks in advance and best ragards
Hi Simon,
Can you actually open a new topic for this?
Thanks :)
Hi Simon,
Please see my reply to your topic:
https://generatepress.com/forums/topic/add-custom-image-id-to-featured-images-and-nowhere-else/#post-1730487
Thanks. :)