本节介绍媒体库中图片的处理,如果你想显示位于主题目录中的图片文件,只需用img标签指定位置,并用CSS进行样式设置。
<img alt="" src="" />
获取img代码
要显示媒体库中的图片,使用wp_get_attachment_image()
函数。
echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );
你将得到以下具有所选缩略图尺寸的HTML输出
<img width="150" height="150" src="http://example.com/wordpress/wp-content/uploads/2016/11/sample-150x150.jpg" class="attachment-thumbnail size-thumbnail" ... />
你可以指定其他尺寸,如原始图片的"full"或在管理界面的设置>媒体中设置的"中"和"大"尺寸,或任何一对宽度和高度的数组。你也可以用add_image_size()自由地设置自定义尺寸字符串。
echo wp_get_attachment_image( $attachment->ID, Array(640, 480) );
获取图片URL
如果你想要获取图片的URL,使用wp_get_attachment_image_src()
,它会返回一个数组(URL, width, height, is_intermediate),如果没有可用的图片,则返回false
$image_attributes = wp_get_attachment_image_src( $attachment->ID ); if ( $image_attributes ) : ?> <img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>" /> <?php endif; ?>
对齐方式
当在你的网站上添加图片时,你可以指定图片的对齐方式为右、左、居中或无。WordPress内核会自动添加CSS类来对齐图片。
- alignright
- alignleft
- aligncenter
- alignnone
这是选择居中对齐时的输出样本:
<img class="aligncenter size-full wp-image-131" src= ... />
为了利用这些CSS类的对齐和文字包装的优势,你的主题必须在一个样式表中包含这些样式,比如主样式表文件。你可以使用官方主题(如Twenty Seventeen)捆绑的style.css
作为参考。
标题
如果在媒体库中为图片指定了一个标题,HTML img
元素被短码和所包围。
<div class="mceTemp"><dl id="attachment_133" class="wp-caption aligncenter" style="width: 1210px"><dt class="wp-caption-dt"><img class="size-full wp-image-133" src="http://example.com/wordpress/wp-content/uploads/2016/11/sample.jpg" alt="sun set" width="1200" height="400" /></dt><dd class="wp-caption-dd">Sun set over the sea</dd></dl></div>
而且,它将在HTML中被呈现为figure标签:
<figure id="attachment_133" style="width: 1200px" class="wp-caption aligncenter"> <img class="size-full wp-image-133" src="http://example.com/wordpress/wp-content/uploads/2016/11/sample.jpg" alt="sun set" width="1200" height="400" srcset= ... /> <figcaption class="wp-caption-text">Sun set over the sea</figcaption> </figure>
与对齐方式类似,你的主题必须包括以下样式。
wp-caption
wp-caption-text
支持WebP和子尺寸图片输出的默认MIME类型
WordPress 5.8引入了对WebP图像格式的支持,它为网络上的图像提供了更好的无损和有损压缩。WebP图像平均比JPEG或PNG图像小30%左右,从而使网站的速度更快,使用的带宽更少。据caniuse称,所有现代浏览器都支持WebP。
当图片被上传时,WordPress会按照add_image_size()的定义生成更小的子尺寸。默认情况下,WordPress将以与原图相同的格式生成这些子尺寸。由于WebP格式的性能优势,用WebP而不是原始格式来生成子尺寸可能是可取的。
image_editor_output_format
过滤钩可以用来改变图像子尺寸的文件格式。这可以用来将所有子尺寸切换为WebP,或任何其他所需的格式(JPEG等)。
下面的例子展示了如何使用WebP生成JPG图像的所有子尺寸。
<?php function wporg_image_editor_output_format( $formats ) { $formats['image/jpg'] = 'image/webp'; return $formats; } add_filter( 'image_editor_output_format', 'wporg_image_editor_output_format' );
注意:GD和ImageMagick库都支持有损和无损的WebP格式。然而,只有ImageMagick支持动画图像。
将输出格式设置为WebP将验证网络服务器是否支持它,如果不支持,它就不会改变格式,也就是说,不会工作。