0

I am new to WP Development and am trying to accomplish something: I would like to add a particular CSS class only to certain featured images.

Specifically, if a featured image is above a certain dimension (say 1000x1000), then I would like to add the css class "full" to it. Ideally, I would like to have the option of manually choosing to add the class or not (but also curious how one would automate this).

How can I go about achieving this?

Thanks!

2 Answers 2

0

One option would be to do it client-side via javascript - set up some javascript to run after the page loads and cycle through all featured images that are on the page, get their dimensions and then add the class as need be. You can use the img.naturalWidth and img.naturalHeight parameters of the image element, and the use addClass('full') to add the class if the image's height and width are large enough.

4
  • Great idea, but what file am I editing to include the JavaScript? I'm assuming the essential "post.php" and "blog.php" files?
    – Alex
    Oct 28, 2015 at 0:38
  • You could probably just edit your theme's main javascript file, if it's included on every page. You might need to edit other php files if you need to add a class to the featured images to make it easier to loop through them. Oct 28, 2015 at 0:57
  • You might need to edit other php files if you need to add a class to the featured images to make it easier to loop through them. @aric-watson do you mind re-phrasing that? if the theme's main js file is included on the relevant php files, what other modifications must I make to those php files?
    – Alex
    Oct 28, 2015 at 1:05
  • It's hard to know w/out seeing your actual site, but I thought you might need to edit some theme files to ensure that your featured images are easy to pick out with jQuery. In other words, you don't want to cycle through all images on the page checking dimensions - it'd be much more efficient to be able to pick out all images that have a featured class (for example) - and to do that you might need to edit a theme file. Oct 28, 2015 at 13:10
0

If you want to automatically add it, wp_get_attachment_image_src() could be a help for you.

In the file where your loop happens, probably index.php or whatever, you could do something like the following:

$your_image = wp_get_attachment_image_src($postID, 'full');

echo '<img src="'.$your_image[0].'" ';
if(($your_image[1] >= 1000) && ($your_image[2] >= 1000)) { echo 'class="full"'; }
else { echo 'class="not-full"; }
echo ' />';

It would check if your image is wider and higher than 1000 px, and if that´s the case, add the class to it.

Could be improved, but should give you an idea about what you could do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.