Wordpress替换图像的默认宽度和高度值


Wordpress replace default width and height values for images

我想替换Wordpress中可视化编辑器添加的默认widthheight值。

我正在使用add_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( '/'s*(?:(?:width=|height=)"('d*)")/', 'style="max-width: ${1}px; max-height: ${2}px;"', $html );    
  return $html;
}

输入字符串为:

<img src="path/to/image.png" alt="" width="300" height="71" class="random-class pull-left" />

也可能包含包裹的a标签。

我希望输出为:

<img ..... style="max-width: 300px; max-height: 71px;">

不使用交替,只需匹配宽度和高度并捕获数字。

$html = preg_replace('/width="('d+)"'s*height="('d+)"/', 'style="max-width: $1px; max-height: $2px;"', $html);