2015-09-06 65 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

相关问题