I have a function that wraps images in a custom div.
It’s placed in functions.php and modifies all posts. I’d like to know if there’s a way to only apply it to posts in a certain category.
Here’s the function:
function my_image_tag($html, $id , $alt, $title) {
$html = "<div class="my-class">" . $html . "</div>";
return $html;
}
add_filter('get_image_tag','my_image_tag',10,4);
Update:
Robert Hue’s method didn’t work with this function, but it worked with the following function, which I think is better (at least for my use):
function wrapImagesInDiv($content) {
if ( in_category( 'prosjekter' ) ) {
$pattern = '/(<img[^>]*class=\"([^>]*?)\"[^>]*>)/i';
$replacement="<div class="image-container $2">$1</div>";
$content = preg_replace($pattern, $replacement, $content);
}
return $content;
}
add_filter('the_content', 'wrapImagesInDiv');