web-dev-qa-db-ja.com

すべての添付ファイルの表示と最後の画像へのクラスの割り当て

私はリストの最後の画像としてマークするためにclass="last"属性を持つ最後の画像を持つリストの中の現在の投稿(またはページ)のためのすべての画像添付ファイルを表示したいというget_images()関数を持っています。

以下のコードは添付された画像を表示させるための私の最初のパスです。

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" />';
    }
  }
}
2
Scott B

これでうまくいくはずです。

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.'" />';
    }
  }
}
1
goldenapples