2

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

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 );
  • This doesn't seem to work. I tried both ID and slug. Does the placement of this function have anything to say? – Garland Briggs Sep 3 '14 at 10:33
  • If your code is working then it should work too... I only added category condition in this function. – Robert hue Sep 3 '14 at 10:40
  • Hm. Quite sure it's not working. I have it in functions.php, perhaps I should try placing it in the loop? Will report back if I have any progress. – Garland Briggs Sep 3 '14 at 11:28
  • This tag can be used to test the current post within The Loop or outside the Loop during a single post request. You can use it anywhere if you specify which post you want to test. – Robert hue Sep 3 '14 at 11:37
  • Check edit in answer. – Robert hue Sep 3 '14 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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