I want to replace the default width
and height
values that are added by the visual editor in Wordpress.
I am using the add_filter
function:
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
and my function is:
function remove_width_attribute( $html ) {
$html = preg_replace( '/\s*(?:(?:width=|height=)"(\d*)")/', 'style="max-width: ${1}px; max-height: ${2}px;"', $html );
return $html;
}
Input string is:
<img src="path/to/image.png" alt="" width="300" height="71" class="random-class pull-left" />
May also contain a
tags wrapped around.
I want the output to be:
<img ..... style="max-width: 300px; max-height: 71px;">
Instead of using alternation, just match the width then height and capture the digits.
$html = preg_replace('/width="(\d+)"\s*height="(\d+)"/', 'style="max-width: $1px; max-height: $2px;"', $html);