1、在模板文件functions.php加入获图方法代码
//获取文章中的图片
function getPatternMatchImages($post_content)
{
$imgSrcArr = array();
//首先将富文本字符串中的 img 标签进行匹配
$pattern_imgTag = '/<img\b.*?(?:\>|\/>)/i';
preg_match_all($pattern_imgTag, $post_content, $matchIMG);
if (isset($matchIMG[0])) {
foreach ($matchIMG[0] as $key => $imgTag) {
//进一步提取 img标签中的 src属性信息
$pattern_src = '/\bsrc\b\s*=\s*[\'\"]?([^\'\"]*)[\'\"]?/i';
preg_match_all($pattern_src, $imgTag, $matchSrc);
if (isset($matchSrc[1])) {
foreach ($matchSrc[1] as $src) {
//将匹配到的src信息压入数组
$imgSrcArr[] = $src;
}
}
}
}
return $imgSrcArr;
}
2、在要调用图片地址的时候引用方法如下
getPatternMatchImages(get_the_content())[0];
上面为获取第一张,第二张为getPatternMatchImages(get_the_content())[1];以些类推
3、如何想要知道文章中有多少图片
<?php
$arraylength = count(getPatternMatchImages(get_the_content()));
echo $arraylength;//图片数量
?>
本文介绍如何在WordPress主题的functions.php文件中添加函数,以解析文章内容中的<img>标签获取图片src,并提供获取第一张、多张图片的方法,同时演示了计算文章图片总数的代码。

1803

被折叠的 条评论
为什么被折叠?



