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');

1 Answer
1

You should check for category posts to modify content. Specify category ID (integer), name or slug (string), or an array of these in in_category check.

function my_image_tag( $html, $id , $alt, $title ) {
    if ( in_category( '1' ) ) {
        $html = "<div class="my-class">" . $html . "</div>";
    }
    return $html;
}

add_filter( 'get_image_tag', 'my_image_tag', 10 ,4 );

For category slug blog-post you can use in_category( 'blog-post' )

If you want to use more then 1 category then you can do something like.

in_category( array( '15', 'Tropical Birds', 'small-mammals' ) )

It’s a combination of ID, Name and slug. SO it’s up to you how you can to use it.

EDIT

If you are using this outside loop then try this.

function my_image_tag( $html, $id , $alt, $title ) {
    global $post;
    if ( in_category( '1' ) ) {
        $html = "<div class="my-class">" . $html . "</div>";
    }
    return $html;
}
add_filter( 'get_image_tag', 'my_image_tag', 10 ,4 );

Leave a Reply

Your email address will not be published. Required fields are marked *