0

The code in question →

<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>

The generated output in browser is like this →

<img width="1620" height="973" src="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" srcset="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg 1620w, http://......./site04/wp-content/uploads/2018/01/audi_ileana-300x180.jpg 300w, ....../site04/wp-content/uploads/2018/01/audi_ileana-768x461.jpg 768w, http://....../site04/wp-content/uploads/2018/01/audi_ileana-1024x615.jpg 1024w" sizes="(max-width: 1620px) 100vw, 1620px">

Anticipated result →

I want that height should output as "auto" value.


I tried this:

<div class="pimg">
    <?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>
</div>

and its css:

.pimg img {max-with:100%; height:auto;}
2

You can use a filter to remove height and width attributes from images, as explained in this CSS Tricks. Place the following in your themes functions.php file.

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}
  • Is it safe to touch the core functions written by Automattic team? Are their any repercussion? – The WP Intermediate Jan 4 '18 at 13:39
  • 1
    @TheWPNovice Filters where introduced to do exactly that. The repercussions are that you might break things, this is always a possibility. But in a case like this I'd guess you're fine – kero Jan 4 '18 at 15:38
1

Alternatively you could try using another function to get just the url then echo that inside img:

<img src="<?php echo get_the_post_thumbnail_url(); ?>" alt="Post thumbnail image">

And style it completely yourself.

  • Yes, yes, but you forget to put that into esc_url → <img src="<?php echo esc_url(get_the_post_thumbnail_url()); ?>" alt="Post thumbnail image"> – The WP Intermediate Jan 4 '18 at 15:44

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.