4

I'm trying to add a CSS class to every image in a custom post type.

I've found this answer, to add a class to every image in general:

function add_image_class($class){
    $class .= ' additional-class';
    return $class;
}
add_filter('get_image_tag_class','add_image_class');

How would I build on this, so that it only applies to a custom post type?

5

Combining the answer here by @cjcj with the code in this answer, the code that works for me outside the loop, in functions.php is:

// Add ability to check for custom post type outside the loop. 
function is_post_type($type){
    global $wp_query;
    if($type == get_post_type($wp_query->post->ID)) return true;
    return false;
}

// Add class to every image in 'wpse' custom post type.
function add_image_class($class){
    if ('wpse' == is_post_type()){
        $class .= ' additional-class';
    }
    return $class;
}
add_filter('get_image_tag_class','add_image_class');
3

The function get_post_type returns the type of the current post, so supposing you want to add this class only to a post type called 'wpse' you should include a conditional like this:

function wpse237573_add_image_class($class){
    if ('wpse' == get_post_type()) $class .= ' additional-class';
    return $class;
}
add_filter('get_image_tag_class','wpse237573_add_image_class');
  • Thank you @cjbj. This works, but only within in the loop. I want to put the code in my functions.php, where it's not working like this. But you helped me in the right direction and I combined your answer with this post to a working solution. I'll share it as a new answer below. – Dvaeer Aug 30 '16 at 9:20

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.