2013-12-18 41 views
8

我已經將圖像上傳到Wordpress媒體庫。從Wordpress媒體庫中獲取單個特定圖像

我知道我可以查看圖像,然後獲取該圖像的URL,然後使用img html標籤在頁面上顯示此圖像。

但是,這並沒有得到圖像的alt,title,captiondescription

img沒有連接到一個崗位或頁面場,所以我認爲你不能使用Get附件等功能

我想使用的功能,而不是寫出來的靜態img HTML代碼的原因是使它們緩存起來更好,更容易維護,並且在媒體庫中更新了圖像的所有數據,而不必編輯對最終用戶不是想法的HTML代碼。

謝謝你提前。

回答

7

第一獲取圖像

function get_images_from_media_library() { 
    $args = array(
     'post_type' => 'attachment', 
     'post_mime_type' =>'image', 
     'post_status' => 'inherit', 
     'posts_per_page' => 5, 
     'orderby' => 'rand' 
    ); 
    $query_images = new WP_Query($args); 
    $images = array(); 
    foreach ($query_images->posts as $image) { 
     $images[]= $image->guid; 
    } 
    return $images; 
} 

和顯示圖像

function display_images_from_media_library() { 

    $imgs = get_images_from_media_library(); 
    $html = '<div id="media-gallery">'; 

    foreach($imgs as $img) { 

     $html .= '<img src="' . $img . '" alt="" />'; 

    } 

    $html .= '</div>'; 

    return $html; 

} 

,並使用PHP的火災事件

<?php echo display_images_from_media_library(); ?> 

或使用該功能

<?php 

if ($attachments = get_children(array(
'post_type' => 'attachment', 
'post_mime_type'=>'image', 
'numberposts' => 1, 
'post_status' => null, 
'post_parent' => $post->ID 
))); 
foreach ($attachments as $attachment) { 
echo wp_get_attachment_link($attachment->ID, '' , true, false, 'Link to image attachment'); 
} 

?> 
13

我認爲你有一個附件ID?你有沒有嘗試過使用附件功能?

食典:

注意,媒體項目也「帖子」在自己的權利,並可以通過WordPress模板層次顯示爲這樣的 。主題可以使用 來循環播放媒體項目或創建畫廊。

以下功能應該讓你開始:

可以檢索圖片src使用:wp_get_attachment_image_src()

$img= wp_get_attachment_image_src($attachmentID, $imageSizeName); 

你可以使用get圖片標題:get_post_field()

get_post_field('post_excerpt', $attachmentID) 

你可以得到alt使用標籤:get_post_meta()

get_post_meta($attachmentID, '_wp_attachment_image_alt', true); 
+0

這個答案對我的作品最好,謝謝。 –

+1

但是你在哪裏獲得附件的實際ID? – Philip

+0

當您在媒體庫中查看圖像時,您可以在瀏覽器欄的URL中看到附件ID。 – Tamara

0

請嘗試下面的代碼:

<?php 
     $attachmentID = 1875; 
     $imageSizeName = "thumbnail"; 
     $img = wp_get_attachment_image_src($attachmentID, $imageSizeName); 
     //print_r($img); 
?> 

<img src="<?php echo $img[0]; ?>" alt="image"> 
相關問題