2014-02-20 54 views
2

我對WordPress CMS比較陌生,並決定將Pod用於包括多個圖像字段的自定義字段實現。雖然我喜歡管理用戶界面,但我有點心煩意亂地嘗試在我的發佈模板文件中輸出圖像。在您的模板文件中顯示基於Pod的圖像的最佳方式

經過大量的研究和實驗,我想分享我使用的技術。顯然,如果有更好的方法我很想知道。

回答

1

我學到的第一件事from the Pods forum是Pods將圖像保存爲數據庫的'Attachment'帖子。因此,您可以像訪問任何常規的舊WordPress附件一樣訪問它們。

附件與他們的職位的父子關係,這意味着你可以通過編程抓住所有的附件使用這個片段改編自WP beginners特定職位:

<?php 
if ($post->post_type == 'post-type' && $post->post_status == 'publish') { 
    $attachments = get_posts(array(
     'post_type' => 'attachment', 
     'posts_per_page' => -1, 
     'post_parent' => $post->ID, 
     'exclude'  => get_post_thumbnail_id() 
    )); 

    if ($attachments) { 
     foreach ($attachments as $attachment) { 
      $class = "post-attachment mime-" . sanitize_title($attachment->post_mime_type); 
      $thumbimg = wp_get_attachment_image($attachment->ID, 'thumbnail'); 
      echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>'; 
     } 

    } 
} 
?> 

但這種方法是次優的,因爲如果從媒體庫中刪除圖像,則只能破壞帖子和圖像之間的父子關係。所以:

  1. 從中去除影像的原有職務,但以備將來使用圖書館留下仍將通過上面的代碼輸出在原來的崗位
  2. 如果你重新用在不同崗位的圖像上面的代碼的Pod字段不會將其打印在新條目中。
  3. 附件系統不記錄字段級關係。因此,如果您在Post上有多個基於圖像的Pod域,則上面的代碼將全部打印出來,而不管它們的域是什麼。

這就是說,我已經發現用於通過場輸出基於波德圖像數據中的最好的選擇是,如下所示概述here on the WordPress support forums與「wp_get_attachment_image」功能的「get_post_meta」功能相結合。

<?php 
if (get_post_meta(get_the_ID(), 'image_field', false)){ 
    $image_array = get_post_meta(get_the_ID(), 'image_field', false); 
} 
if ($image_array) { 
    echo '<ul>'; 
    foreach ($image_array as $image) { 
     $class = "post-attachment mime-" . sanitize_title($image->post_mime_type); 
     $thumbimg = wp_get_attachment_image($image['ID'], 'thumbnail'); 
     echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>'; 
    } 
    echo '</ul>'; 
} 
?> 

前一個函數爲您提供一個只包含當前圖像的對象。後者呈現這些圖像的大小和其他信息僅限於附件系統。

相關問題