ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 图片 >[warning] 注意:本节介绍媒体库中图像的处理。 如果要显示位于主题目录中的图像文件,只需使用img标签指定位置,并使用CSS进行样式化。 ``` <img src="<?php echo get_template_directory_uri() . '/images/logo.png'; ?>" /> ``` ## 获取图片代码 要在媒体库中显示图像,请使用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”或“medium”和“large”。 您还可以使用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类用于对齐和文本换行,您的主题必须包含样式表中的样式,如主样式表文件。 您可以使用与官方主题捆绑的style.css,如Twenty Seventeen为参考。 ## 标题 如果在媒体库中指定了图像图像,则HTML img元素由短代码`[caption]`和`[/ caption]`括起来。 ``` <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 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 ## 参考文献 wp_get_attachment_image() wp_get_attachment_image_src()