2012-04-30 76 views
4

在WordPress中獲取圖片附件網址時有點麻煩。這是我的代碼到目前爲止:WordPress的獲取圖片網址(目前正在使用wp_get_attachment_url)

<?php // find images attached to this post/page. 
      global $post; 
      $thumb_ID = get_post_thumbnail_id($post->ID); 
      $args = array(
       'post_type' => 'attachment', 
       'post_mime_type' => 'image', 
       'numberposts' => -1, 
       'orderby' => 'menu_order', 
       'order' => 'ASC', 
       'exclude' => $thumb_ID, 
       'post_parent' => $post->ID 
      ); 
      $images = get_posts($args); 
      ?> 

      <?php // Loop through the images and show them 

      if($images) 
      { 
      foreach($images as $image) 
      { 

      echo wp_get_attachment_image_url($image->ID, $size='attached-image'); 

      } 
      } 

?> 

它什麼都不返回。如果我換出wp_get_attachment_image_url($image->ID, $size='attached-image');wp_get_attachment_image($image->ID, $size='attached-image');這工作正常,但帶來的形象,而不僅僅是網址。

+2

我相信你正在尋找'wp_get_attachment_url($ ID);'或'wp_get_attachment_image_src($ attachment_id,$大小,$圖標);'而是 - 你所引用的函數不是一個WP功能。 –

+0

對不起,我對PHP相當陌生。我將如何使用上面的代碼來遍歷所有圖像並輸出url? – Alfazo

+0

在閱讀您的評論和您的問題後,我意識到可能還有其他事情正在發生:您是想要所有的附加圖片,還是隻想要特色圖片?您的代碼'get_post_thumbnail_id'只能獲取精選圖片。您的評論建議您希望查看該帖子的所有圖片 - 是嗎? –

回答

7

以下代碼將遍歷所有圖像附件並輸出src url。請注意,根據您的需要顯示了兩種方法。

<?php 

    global $post; 
    $args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_mime_type' => 'image', 'post_status' => null, 'post_parent' => $post->ID); 
    $attachments = get_posts($args); 
    if ($attachments) { 
      foreach ($attachments as $attachment) { 
        // Method #1: Allows you to define the image size 
        $src = wp_get_attachment_image_src($attachment->ID, "attached-image"); 
        if ($src) {echo $src[0];} 
        // Method #2: Would always return the "attached-image" size 
        echo $attachment->guid; 
      } 
    } 

?> 
+0

謝謝!我設法使用wp_get_attachment_src來實現類似的功能,但方式稍有不同。你的方式更清潔,所以謝謝你! – Alfazo

+0

附件的GUID屬性就是這樣的一個GUID--它不應該被當作一個可以在任何地方使用的URL。最後一行'echo $ attachment-> guid'可以取代實際上不會成爲真正URL的URL。請參閱http://pods.io/2013/07/17/dont-use-the-guid-field-ever-ever-ever/ – Will