phpwordpressimageclassorientation

Adding Class to img Container based on Post Thumbnail Orientation


I have a script in my functions that adds a class to the featured image based on whether it is landscape or portrait. It works by measuring the height against the width of given post thumbnail and appending the class from attachment- into horizontal-image attatchment-.

if ( ! function_exists( 'mytheme_vertical_check' ) ) :
    function mytheme_vertical_check( $html, $post_id, $post_thumbnail_id, $size, $attr ) {

        $image_data = wp_get_attachment_image_src( $post_thumbnail_id , 'large' );

        //Get the image width and height from the data provided by wp_get_attachment_image_src()
        $width  = $image_data[1];
        $height = $image_data[2];

        if ( $width > $height ) {
            $html = str_replace( 'attachment-', 'horizontal-image attachment-', $html );
        }
        return $html;
    }
endif;

add_filter( 'post_thumbnail_html', 'mytheme_vertical_check', 10, 5 );

However, instead of adding horizontal-image to the actual IMG class, I need it to be added to the container's class. The container is a div with the class masonry-thumbnail. So I would like the appropriate containers to instead have masonry-thumbnail horizontal as their class.

Note: The original writer of this function suggested that I used a jQuery fix, and after trying several different strings of code, I realized that it did not work well with Infinite Scroll and would therefore be better of with the modification coming from inside WordPress itself by way of functions, just like the original code (which works perfectly) appending the class when the page initially renders, as opposed to post-page load through jQuery. Besides, I'd like to use as little JavaScript as possible.


Solution

  • You could try something like this. Modify your function to return only 'horizontal' class if image is landscape:

    function mytheme_vertical_check() {
    
        $thumb_id   = get_post_thumbnail_id();
        $image_data = wp_get_attachment_image_src( $thumb_id , 'tp-thumbnail' );
    
        $width  = $image_data[1];
        $height = $image_data[2];
    
        if ( $width > $height ) {
            return 'horizontal';
        }
    }
    

    And inside the loop call it to add 'horizontal' class to a div of your choice:

    <?php if ( has_post_thumbnail() ) : ?>
        <?php printf( '<div class="masonry-thumbnail %s">', mytheme_vertical_check() );?>
            <?php the_post_thumbnail( 'large' ); ?>
        </div>
    <?php endif; ?>