Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Pascal Hausberger
Pascal Hausberger
16,453 Points

WP: Wrapping images with CSS class

Hi,

I'm trying to add a Bootstrap CSS class to each image that I insert into a blog post, however, I don't know how to do this.

With the thumbnail, it was easy, since i could simply:

<?php the_post_thumbnail( 'thumbnail-custom', array( 'class' => 'headerImg img-responsive' ) ); ?>

However, I couldn't find a similar code for the_content().

Does anyone know how to fix this?

Maybe a loop to find every single image and then add the CSS class to each one of them?

Thank you!

Cheers, pascal

2 Answers

Boris Kamp
Boris Kamp
16,660 Points

Hi Pascal,

are you talking about pictures inserted into the wp editor when publishing a post? The way I do stuff like this is with Javascript & jQuery. Off course you can manually add the class by editing the picture in WP, but that takes a lot of time and is a bad approach if you need consistent attributes added.

So I do it this way, add something like this:

$('.#content-wrapper img').addClass('img-responsive');

I don't know if you know JS? if not, this code searches for all the images within the wrapper #content-wrapper (edit this to your needs) and adds the class img-responsive to all the images. If you don't know Javascript, take some courses here, you'll thank yourself afterwards for doing so.

Pascal Hausberger
Pascal Hausberger
16,453 Points

Ah thanks a lot, Boris!!! Yeah, I do use js, so this would be a great solution! :)

Boris Kamp
Boris Kamp
16,660 Points

Your welcome! just make sure to limit your scope if needed by using specific wrappers or something. Otherwise ALL your images on the HTML page (including logo's etc) will be tagged with that new class.