0
add_action( 'content_save_pre', 'add_image_dimensions' );

function add_image_dimensions( $content ) {

    preg_match_all( '/<img[^>]+>/i', $content, $images);

    if (count($images) < 1)
        return $content;

foreach ($images[0] as $image) {
    preg_match_all( '/(alt|title|src|width|class|id|height)=("[^"]*")/i', $image, $img );

    if ( !in_array( 'src', $img[1] ) )
        continue;

    if ( !in_array( 'width', $img[1] ) || !in_array( 'height', $img[1] ) ) {
        $src = $img[2][ array_search('src', $img[1]) ];
        $alt = in_array( 'alt', $img[1] ) ? ' alt=' . $img[2][ array_search('alt', $img[1]) ] : '';
        $title = in_array( 'title', $img[1] ) ? ' title=' . $img[2][ array_search('title', $img[1]) ] : '';
        $class = in_array( 'class', $img[1] ) ? ' class=' . $img[2][ array_search('class', $img[1]) ] : '';
        $id = in_array( 'id', $img[1] ) ? ' id=' . $img[2][ array_search('id', $img[1]) ] : '';

        list( $width, $height, $type, $attr ) = getimagesize( str_replace( "\"", "" , $src ) );
        $html = '';

        if (($width != 0) || ($height != 0)) {
            $html = ' width="%d" height="%d" ';
        }

        $image_tag = sprintf( '<img loading="lazy" src=%s%s%s%s%s' . $html . '/>', $src, $alt, $title, $class, $id, $width, $height );
        $content = str_replace($image, $image_tag, $content);
    }
}

return $content;
}

This code should add width and height to pictures when saving post, but it doesn't. Why?

Help me please.

Sorry for my English.

9
  • 1
    notice that you modify $content but then you don't return it, filters always return something. If you don't return something, then it's the same as return '';
    – Tom J Nowell
    May 27, 2021 at 16:21
  • How will it be correct? May 28, 2021 at 5:42
  • hmm you do return the content, I didn't notice because of the incorrect indentation, so that's not the cause, please ignore my first comment
    – Tom J Nowell
    May 28, 2021 at 12:18
  • Can I ask why you used content_save_pre? I checked the official WP docs and could not find that filter, and Adam Browns hooks database suggests it's not used in post saving. WP image blocks should also be adding widths and heights as well as srcset attributes by default
    – Tom J Nowell
    May 28, 2021 at 12:20
  • I saw this hook here wordpress.stackexchange.com/questions/21805/… And I insert pictures directly into the article May 28, 2021 at 15:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.