すべての投稿添付ファイルを表示し、クラスを最後の画像に割り当てますか?

wordpress.stackexchange https://wordpress.stackexchange.com/questions/3016

  •  16-10-2019
  •  | 
  •  

質問

機能があります get_images() 現在の投稿(またはページ)のすべての画像添付ファイルをリストに表示したいと思います。最後の画像には class="last" リストの最後の画像としてマークする属性。

以下のコードは、添付の画像を表示するための最初のパスですが、ループから1つの画像をリストしているので、私の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帰属
所属していません wordpress.stackexchange
scroll top