在制作wordpress主题过程中,有遇见想要自动获取文章内所有图片的情况,一开始没有思路,后来,想起大前段的xiu主题貌似就拥有这样的功能,经过维维大神的扣扯后,现在大叔拿来分享哈,绝笔可用的嚎!
将代码插入functions.php
function hui_get_thumbnail( $single=true, $must=true ) { global $post; $html = ''; if ( has_post_thumbnail() ) { $domsxe = simplexml_load_string(get_the_post_thumbnail()); $src = $domsxe->attributes()->src; $src_array = wp_get_attachment_image_src(hui_get_attachment_id_from_src($src), 'thumbnail'); $html = sprintf('<li><img src="%s" /></li>', $src_array[0]); } else { $content = $post->post_content; preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER); $images = $strResult[1]; $counter = count($strResult[1]); $i = 0; foreach($images as $src){ $i++; $src2 = wp_get_attachment_image_src(hui_get_attachment_id_from_src($src), 'thumbnail'); $src2 = $src2[0]; if( !$src2 && true ){ $src = $src; }else{ $src = $src2; } $item = sprintf('<li><img src="%s" /></li>', $src); if( $single){ return $item; break; } $html .= $item; if( ($counter >= 4 && $counter < 8 && $i >= 4) || ($counter >= 8 && $i >= 8) || ($counter > 0 && $counter < 4 && $i >= $counter) ){ break; } } } return $html; } function hui_get_attachment_id_from_src ($link) { global $wpdb; $link = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $link); return $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE guid='$link'"); }
以上代码规则可根据自己实际要求来修改
前端调用
<?php echo hui_get_thumbnail(false,true);?>
未经允许不得转载:窗外天空 » wordpress 获取文章内所有图片