也想出现在这里?联系我们

wordpress 获取文章内所有图片

  • 文章介绍
  • 升级版本
  • 评价&建议

在制作wordpress主题过程中,有遇见想要自动获取文章内所有图片的情况,一开始没有思路,后来,想起大前段的xiu主题貌似就拥有这样的功能,经过维维大神的扣扯后,现在大叔拿来分享哈,绝笔可用的嚎!

20150530163032

将代码插入functions.php

  1. function hui_get_thumbnail( $single=true, $must=true ) {
  2.     global $post;
  3.     $html = '';
  4.     if ( has_post_thumbnail() ) {
  5.         $domsxe = simplexml_load_string(get_the_post_thumbnail());
  6.         $src = $domsxe->attributes()->src;
  7.         $src_array = wp_get_attachment_image_src(hui_get_attachment_id_from_src($src), 'thumbnail');
  8.         $html = sprintf('<li><img src="%s" /></li>', $src_array[0]);
  9.     } else {
  10.         $content = $post->post_content;
  11.         preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content$strResult, PREG_PATTERN_ORDER);
  12.         $images = $strResult[1];
  13.         $counter = count($strResult[1]);
  14.         $i = 0;
  15.         foreach($images as $src){
  16.             $i++;
  17.             $src2 = wp_get_attachment_image_src(hui_get_attachment_id_from_src($src), 'thumbnail');
  18.             $src2 = $src2[0];
  19.             if( !$src2 && true ){
  20.                 $src = $src;
  21.             }else{
  22.                 $src = $src2;
  23.             }
  24.             $item = sprintf('<li><img src="%s" /></li>', $src);
  25.             if$single){
  26.                 return $item;
  27.                 break;
  28.             }
  29.             $html .= $item;
  30.             if(
  31.                 ($counter >= 4 && $counter < 8 && $i >= 4) ||
  32.                 ($counter >= 8 && $i >= 8) ||
  33.                 ($counter > 0 && $counter < 4 && $i >= $counter)
  34.             ){
  35.                 break;
  36.             }
  37.         }
  38.     }
  39.     return $html;
  40. }
  41. function hui_get_attachment_id_from_src ($link) {
  42.     global $wpdb;
  43.     $link = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', ''$link);
  44.     return $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE guid='$link'");
  45. }

以上代码规则可根据自己实际要求来修改

前端调用

  1. <?php echo hui_get_thumbnail(false,true);?>
有用7
  • 2015.05.30初次和大家见面了!

等待您对该主题的建议

发表评论

还能输入240个字

Hi, 欢迎加入Wordpress技术交流群,带你装逼带你飞!

我要入群
也想出现在这里?联系我们
wordpress加速

我来推荐一个更牛逼的给你看看?

  • 猛戳我吧