
有时需要调用文章的几个或者
全部图片,如何实现呢,简单介绍几种方法,都在主题的function.php里扔下述代码。
1、输出img代码
php
//调用文章的全部图片
function all_img($content){
$pattern = '/<img[^>]*src=\"([^\"]+)\"[^>]*\/?>/si';
$matches = array();
if (preg_match_all($pattern, $content, $matches)) {
// 注意,$matches[1]中才是图片地址,可以自己打印看看
// 如果图片小于1,则不显示缩略图
if (count($matches[1] > 1)) {
// 显示4张图片
foreach ($matches[1] as $index => $imgUrl) {
echo "<img src="/%22;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20echo%20$imgUrl;%20//%20%E6%98%BE%E7%A4%BA%E5%9B%BE%E7%89%87%20%20%20%20%20%20%20%20%20%20%20echo%20%22" alt=".get_the_title()." width='23%' height='auto'/>";
// $index为3的时候已经是第四张了($index从0开始的)
if ($index >= 3) {
break;
}
}
}
} else {
// 没有图片了
echo "";
}
}
调用代码
HTML样式为:
html
[img src="http://XXX.COM/XX/XX.PNG" alt="" width="" height="">
2、直接输出图片地址
php
//wordpress调用多张文章图片缩略图
function preview_img($soContent) {
$soImages = '~<img [^\>]*\ />~';
preg_match_all( $soImages, $soContent, $thePics );
$allPics = count($thePics);
if( $allPics > 0 ) {
$count=0;
foreach($thePics[0] as $v) {
if( $count == 5 ) {break;} //图片数量,自行调整
else { echo '<span class="preview-img">',$v,'</span>'; }
$count++;
}
}
}
调用代码
php
<?php preview_img(); ?>
HTML样式为:
html
http://XXX.COM/XX/XX.PNG
根据个人需求选择。