在開發(fā)主題時(shí),我們常常需要調(diào)用自己準(zhǔn)備的圖片,在wordpress主題開發(fā)過程中,該如何調(diào)用呢?這一次的wordpress開發(fā)教程就和大家分享下,怎么調(diào)用主題文件夾里的圖片。
- 函數(shù)文檔:官方文檔
根據(jù)下方代碼演示,您可以根據(jù)自己的需要進(jìn)行調(diào)整使用即可。
<img src="<?php echo get_template_directory_uri() . '/images/logo.png'; ?>" />
?
怎么調(diào)用子主題里的圖片
<img src="<?php echo get_stylesheet_directory_uri();?>/assets/logo.svg" />
當(dāng)然,在函數(shù)中,您哈可以這樣用:
//獲取圖片
$alignleft_logo = get_template_directory_uri() . '/img/alignleft.svg';
調(diào)用:
<img class="img-tags" src="'.$alignleft_logo.'" alt="上一頁(yè)" title="上一頁(yè)"/>
獲取img代碼
要在媒體庫(kù)中顯示圖像,請(qǐng)使用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" ... />
您可以指定其他尺寸,例如原始圖像的“完整”或“中”和“大”,用于在“?管理”屏幕中的“設(shè)置”>“媒體”中設(shè)置的尺寸,或任何寬度和高度對(duì)作為數(shù)組。您還可以使用add_image_size()自由設(shè)置自定義大小字符串;
echo wp_get_attachment_image( $attachment->ID, Array(640, 480) );
獲取圖像的URL
如果要獲取圖像的URL,請(qǐng)使用wp_get_attachment_image_src()
。它返回一個(gè)數(shù)組(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; ?>
路線
在站點(diǎn)中添加圖像時(shí),可以將圖像對(duì)齊指定為right,left,center或none。WordPress核心自動(dòng)添加CSS類來(lái)對(duì)齊圖像:
- alignright
- alignleft
- 居中對(duì)齊
- alignnone
這是選擇中心對(duì)齊時(shí)的樣本輸出
<img class="aligncenter size-full wp-image-131" src= ... />
為了利用這些CSS類進(jìn)行對(duì)齊和文本換行,您的主題必須在樣式表中包含樣式,例如主樣式表文件。您可以使用style.css
捆綁的官方主題,如Twenty Seventeen作為參考。
標(biāo)題
如果在媒體庫(kù)中為圖像指定了標(biāo)題,則HTML?img
元素由短代碼和[/ caption]括起來(lái)。
<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格式呈現(xiàn)為圖形標(biāo)記:
<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>
與對(duì)齊類似,您的主題必須包含以下樣式。
wp-caption
wp-caption-text