2015-09-06 31 views
1

我想要定位Wordpress文章內容中的最後一張圖片。每個帖子都有不同數量的圖片,我想把標題重疊在最後一張。定位WordPress的文章中的最後一張圖片 - undefined amount

我有代碼來定位帖子的第一個圖像,並把重疊的標題放在重疊的div中。問題是我不知道如何改變它來找出並定位最後的圖像。

HTML

 <?php 
      preg_match_all('/(<img [^>]*>)/', get_the_content(), $images); 
      for($i=0; isset($images[1]) && $i < count($images[1]); $i++) { 
       if ($i == 0) { 
       // only printed when looping on 1st image with a wrapped <div> element 
       echo sprintf('<div class="first-img"><h1>%s</h1>%s</div>', get_the_title(), $images[1][$i]); 
       continue; 
      } 
      echo $images[1][$i]; 
      } 
     ?> 

編輯 - 我希望所有的圖片來顯示,但我想指定的最後一個把標題過頂

回答

1

可以使用end PHP函數來獲取圖像數組的最後一個元素。

<?php 
     preg_match_all('/(<img [^>]*>)/', get_the_content(), $images); 
     if(!empty($images[1])){ 
      $last_image = end($images[1]); 
      echo sprintf('<div class="first-img"><h1>%s</h1>%s</div>', get_the_title(), $last_image); 
     } 
    ?> 

http://php.net/manual/en/function.end.php

編輯:如果你希望所有的圖像試試這個:


<?php 
     preg_match_all('/(<img [^>]*>)/', get_the_content(), $images); 
     for($i=0; isset($images[1]) && $i < count($images[1]); $i++) { 
      if ($i == end(array_keys($images[1]))) { 
      // only printed when looping on 1st image with a wrapped <div> element 
      echo sprintf('<div class="first-img"><h1>%s</h1>%s</div>', get_the_title(), $images[1][$i]); 
      continue; 
     } 
     echo $images[1][$i]; 
     } 
    ?> 
+0

與問題是它只顯示最後的圖像,然後,我還是希望所有的圖像顯示 – user3550879

+0

查看答案,我已更新顯示所有圖片 – gskhanal

+0

完美!謝謝 – user3550879

相關問題