2011-11-13 81 views
1

試圖從帖子中獲取第一張圖片,但我的php代碼不會返回任何內容,有幫助嗎?Wordpress從帖子中獲取第一張圖片

<?php while ($browndog_blog->have_posts()) : $browndog_blog->the_post();      
    $args = array(
    'numberposts' => 1, 
    'post_mime_type' => 'image', 
    'post_parent' => $post->ID, 
    'post_status' => null, 
    'post_type' => 'attachment' 
    ); 

    $attachments = get_children($args); 

    //print_r($attachments); 

    if ($attachments) { 
     foreach($attachments as $attachment) { 
      $image_attributes = wp_get_attachment_image_src($attachment->ID, 'thumbnail') ? wp_get_attachment_image_src($attachment->ID, 'thumbnail') : wp_get_attachment_image_src($attachment->ID, 'full'); 

      echo '<a href="'.get_permalink($post->ID).'"><img src="'.wp_get_attachment_thumb_url($attachment->ID).'"></a>'; 
      echo '<p>'.get_the_excerpt($post->ID).'</p>'; 
      echo '<p><a href="'.get_permalink($post->ID).'">Read More</a></p>'; 
     } 
    } 
endwhile; ?> 

不知道發生了什麼事情錯了,因爲我使用了一個類似的代碼來獲取所有圖像附件,而不是隻有一個,那工作正常。

+0

[如何獲得第一張圖片與WP帖子相關聯]的可能重複?(http://stackoverflow.com/questions/2332979/how-to-get-the-first-image-assoc-with-a -wp-POST) – hakre

回答

0

我想我只是做了同樣的事情,你正在尋找做...我不會聲稱是一個上師,但這是我做了什麼來做到這一點工作,並與運氣,你將能夠適應它符合你的需求。

$image_id=get_post_thumbnail_id(); 
$image_url = wp_get_attachment_image_src($image_id,’large’); 
$image_url=$image_url[0]; 

基本上數組中的第一個圖像的縮略圖,按我的理解,所以這就是爲什麼我第一次搶縮圖ID,然後用它來獲取大版本的圖像。

1

get_children()僅返回已直接上傳到該帖子的圖片。如果圖像已附加到給定的帖子,它不會被認爲是它的孩子,因此不會被上述功能返回。

一個簡單的方法來檢查一個職位的孩子是登錄到儀表板並轉到帖子,編輯帖子。點擊編輯器上方的Add Media按鈕,並從唯一的下拉框中選擇Uploaded to this post。如果這是空的,get_children將不會返回任何圖像,而不管帖子的內容。

相關問題