对于任何其他寻求自动化解决方案的人,以确保整个WordPress站点中的所有图像都具有适当的width
和height
属性集,以下插件将为您处理它:Specify Image Dimensions.
您可以查看源代码并将其添加到自己的源代码中functions.php
另一种选择是:
add_action( \'plugins_loaded\', \'factmaven_spcimg_buffer\', 10, 1 );
function factmaven_spcimg_buffer() { // Enable output buffering for our function
ob_start( \'factmaven_spcimg_specify_image_dimensions\' );
}
function factmaven_spcimg_specify_image_dimensions( $content ) { // Automatically insert width and height attributes
if ( is_admin() && ( ! defined( \'DOING_AJAX\' ) || ! DOING_AJAX ) ) { // Don\'t run the function in the admin panel
return $content;
}
preg_match_all( \'/<img[^>]+>/i\', $content, $images );
if ( count( $images ) < 1 ) { // Don\'t change content if there are no images
return $content;
}
foreach ( $images[0] as $image ) {
preg_match_all( \'/(src|alt|title|class|id|width|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 ) );
$image_tag = sprintf( \'<img src=%s%s%s%s%s width="%d" height="%d" />\', $src, $alt, $title, $class, $id, $width, $height );
$content = str_replace( $image, $image_tag, $content );
}
}
return $content;
}