WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Prevent WP to add width/height to img-tags (3 posts)

  1. p0mmeluff
    Member
    Posted 2 years ago #

    When I add a post thumbnail to a post or page, I can choose the size at which it should be displayed (Thumbnail, Medium, Large, Original). WordPress then adds width="xyz" height="abc" to the HTML output.

    In my case however, I do NOT want WordPress to set a specific size and add width/height parameters to the HTML, because I set max-width values via CSS (media queries). While the thumbnail's width is higher then the max-width CSS value (which is intended), it results in a vertically stretched image, because WordPress adds width/height to the <img /> tag.
    So if I could find a way to prevent WordPress to add width/height parameters on post thumbnails, I could scale these images proportional via CSS, without any distortion.

    Any ideas?

  2. andiszek
    Member
    Posted 2 years ago #

    hi there,
    try to use this filter:

    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;
    }

    add it to your functions.php

    regards,
    andi

  3. p0mmeluff
    Member
    Posted 2 years ago #

    Wow, thank you! This works for me. :)

    However, I modified it slightly so that it only removes the attributes on specific pages:

    add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
    add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
    function remove_width_attribute( $html ) {
        if ( !is_page( myPage ) ) {
            return $html;
        } else {
            $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
            return $html;
        }
    }

Topic Closed

This topic has been closed to new replies.

About this Topic