WordPress 主題中顯示圖片的幾種方法

取目前 post「特色圖片」

the_post_thumbnail( 'thumbnail','style=max-width:100%;height:auto;');

返回<img>標籤

<img width="150" height="150" src="https://example.com/wp-content/uploads/2017/11/image-xyz-150x150.jpg" class="attachment-thumbnail size-thumbnail" alt="" srcset="http://example.com/wp-content/uploads/2017/11/image-xyz-150x150.jpg 150w, http://example.com/wp-content/uploads/2017/11/image-xyz-50x50.jpg 50w" sizes="(max-width: 150px) 100vw, 150px" />

取 post「特色圖片」

// without parameter -> Post Thumbnail (as set by theme using set_post_thumbnail_size())
get_the_post_thumbnail( $post_id );                   
 
get_the_post_thumbnail( $post_id, 'thumbnail' );      // Thumbnail (Note: different to Post Thumbnail)
get_the_post_thumbnail( $post_id, 'medium' );         // Medium resolution
get_the_post_thumbnail( $post_id, 'large' );          // Large resolution
get_the_post_thumbnail( $post_id, 'full' );           // Original resolution
 
get_the_post_thumbnail( $post_id, array( 100, 100) ); // Other resolutions

返回<img>標籤

<img width="150" height="150" src="https://example.com/wp-content/uploads/2017/11/image-xyz-150x150.jpg" class="attachment-thumbnail size-thumbnail" alt="" srcset="http://example.com/wp-content/uploads/2017/11/image-xyz-150x150.jpg 150w, http://example.com/wp-content/uploads/2017/11/image-xyz-50x50.jpg 50w" sizes="(max-width: 150px) 100vw, 150px" />

取 post「特色圖片」網址

<?php

/* get a specific post object by ID */
$post = get_post(2);
  
/* grab the url for the full size featured image */
$featured_img_url = get_the_post_thumbnail_url($post->ID, 'full'); 
 
/* link thumbnail to full size image for use with lightbox*/
echo '<a href="'.$featured_img_url.'" rel="lightbox">'; 
    the_post_thumbnail('thumbnail');
echo '</a>';

?>

取媒體圖片

<?php 
echo wp_get_attachment_image( get_the_ID(), array('700', '600'), "", array( "class" => "img-responsive" ) );
?>

返回<img>標籤

<img width="150" height="150" src="https://example.com/wp-content/uploads/2017/11/image-xyz-150x150.jpg" class="attachment-thumbnail size-thumbnail" alt="" srcset="http://example.com/wp-content/uploads/2017/11/image-xyz-150x150.jpg 150w, http://example.com/wp-content/uploads/2017/11/image-xyz-50x50.jpg 50w" sizes="(max-width: 150px) 100vw, 150px" />

取媒體圖片

<?php
$image_id = 123;
$image = wp_get_attachment_image_src( $image_id );
if ( $image ) : ?>
    <img src="<?php echo $image[0]; ?>" width="<?php echo $image[1]; ?>" height="<?php echo $image[2]; ?>" />
<?php endif; ?>

返回陣列

array (size=4)
  0 => string 'http://example.com/wp-content/uploads/2017/11/image-name-150x150.jpg' (length=72)
  1 => int 150
  2 => int 150
  3 => boolean true

WordPress預設圖片尺寸速查表

名稱說明尺寸
thumbnail縮圖150 * 150px
medium300 * 300px
medium_large中大760 * 0px
large1024 * 1024px
full完整

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料