我正在尝试将SVG图像用于wp_get_attachment_image() 但它在网站前端产生了非常奇怪的输出。
为了支持SVG文件类型,我首先在我的主题中添加了以下函数functions.php 文件
/*** enable svg support ***/
function cc_mime_types($mimes) {
  $mimes[\'svg\'] = \'image/svg+xml\';
  return $mimes;
}
add_filter(\'upload_mimes\', \'cc_mime_types\');
 然后在我的主题文件中,我尝试使用如下SVG图像:
$image_id = 3679;
echo wp_get_attachment_image( $image_id, array( 57, 58 ), false, array( "class" => "icon" ) ); 
 因此,它应该生成如下html:
<img width="57" height="58" src="http://example.com/wp-content/uploads/2016/09/something.svg" class="icon">
 但它生成的HTML如下所示:
<img width="1" height="1" src="http://example.com/wp-content/uploads/2016/09/something.svg" class="icon" alt="briefcase">
 正如您所看到的,由于
width="1" 和
height="1", 该图像没有显示出来。但我不明白的是,这个1值是从哪里来的,因为我没有传递它。
有人知道这个问题的解决方法吗?
 
                    最合适的回答,由SO网友:Dave Romsey 整理而成
                    WordPress在SVG的宽度和高度属性方面存在问题。可以使用以下代码删除SVG的宽度和高度属性trac ticket #26256 .
/**
 * Removes the width and height attributes of <img> tags for SVG
 * 
 * Without this filter, the width and height are set to "1" since
 * WordPress core can\'t seem to figure out an SVG file\'s dimensions.
 * 
 * For SVG:s, returns an array with file url, width and height set 
 * to null, and false for \'is_intermediate\'.
 * 
 * @wp-hook image_downsize
 * @param mixed $out Value to be filtered
 * @param int $id Attachment ID for image.
 * @return bool|array False if not in admin or not SVG. Array otherwise.
 */
function wpse240579_fix_svg_size_attributes( $out, $id ) {
    $image_url  = wp_get_attachment_url( $id );
    $file_ext   = pathinfo( $image_url, PATHINFO_EXTENSION );
    if ( is_admin() || \'svg\' !== $file_ext ) {
        return false;
    }
    return array( $image_url, null, null, false );
}
add_filter( \'image_downsize\', \'wpse240579_fix_svg_size_attributes\', 10, 2 );