WordPress.org

Ready to get started?Download WordPress

Forums

Adding Class to Container based on Post Thumbnail Orientation (2 posts)

  1. azor_ahai
    Member
    Posted 2 months ago #

    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.

    I thought this would be a simple problem to solve, but days have now passed and I'm losing hair. If anybody can lend a hand, or point me in the right direction, that would be fantastic. Thank you.

  2. bcworkz
    Member
    Posted 2 months ago #

    You need to locate the code that outputs the container tag. If it is in the "Loop", you can obtain featured image data the same way your current code does. If it is outside the "Loop", jQuery is likely your only recourse.

Reply

You must log in to post.

About this Topic