Site icon Anthony Carbon

How to add, remove, replace a classes in image using the_post_thumbnail()?

How to add, remove, replace a classes in image using the_post_thumbnail()? Let’s say we have this classes in image object.

<img class="attachment-to-be-replace size-to-be-replace wp-post-image" src="https://www.anthonycarbon.com/wp-content/uploads/image.jpg" alt="" width="800" height="600" >

To replace the class name “to-be-replace”, copy this code to your functions.php

add_filter( 'wp_get_attachment_image_attributes', function($attr){
	$attr['class'] = str_replace( 'to-be-replace', 'hello-world', $attr['class'] );
	return $attr;
});

Output is:

<img class="attachment-hello-world size-hello-world wp-post-image" src="https://www.anthonycarbon.com/wp-content/uploads/image.jpg" alt="" width="800" height="600" >
Exit mobile version