我有一个功能 get_images() 我想在其中显示当前帖子(或页面)的所有图像附件,其中最后一个图像具有 class="last" 将其标记为列表中的最后一个图像。

下面的代码是我的第一个通行证,即显示附件的图像,但是它唯一将一个图像从循环中列出,因此我的foreach被抛弃了...

function get_images() {
  global $post;
  $attachment = array_values(get_children(array( 
    'post_parent' => $post->ID, 
    'post_type' => 'attachment', 
    'post_mime_type' => 'image', 
    'order' => 'ASC', 
    'numberposts' => 1 
  )));
  if ( $attachment ) {
    foreach($attachment as $attachmentImage) {
      echo '<img src="' . wp_get_attachment_url($attachmentImage->ID) . 
        '" class="post-attachment" />';
    }
  }
}
有帮助吗?

解决方案

我认为这应该做到:

function get_images() {
  global $post;
  $attachment = get_children(array( 
      'post_parent' => $post->ID, 
      'post_type' => 'attachment', 
      'post_mime_type' => 'image', 
      'order' => 'ASC', 
      'numberposts'  => -1 ), 
    ARRAY_N );
  if ( $attachment ) {
    $attachment_count = count($attachment);
    foreach($i=0; $i < $attachment_count; $i++) {
      $last = ($i == ($attachment_count-1) ) ? ' last' : '';
      echo '<img src="' . wp_get_attachment_url($attachment[$i]->ID) . 
        '" class="post-attachment'.$last.'" />';
    }
  }
}
许可以下: CC-BY-SA归因
scroll top