博客簿

wordpress 获取文章内所有图片

时间:4年前   阅读:7417

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

 wordpress 获取文章内所有图片 wordpress教程

将代码插入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);?>

上一篇:wordpress分页的极简实现

下一篇:wordpress主题 仪表盘 添加站外文章列表

网友评论