wordpress判断文章中是否存在图片其及调用

对文章中是否存在图片的判断,在我们制作杂志类页面中经常遇到,很实用。直接上代码了。

方法一:

1、在functions.php添加代码

//判断文章中是否有图片

function is_has_image(){
if(is_single()||is_page()){
global $post;
if(has_post_thumbnail()) return true;
$content=$post->post_content;
preg_match_all('//sim',$content,$strResult,PREG_PATTERN_ORDER);

if(!empty($strResult[1])) return true;
return false;
}
}
2、需要的div函数调用
<?phpif(is_has_image()):

?> ......//功能代码
<?phpendif;?>
方法二:

//判断文章中是否含有图片
functiondon_the_thumbnail(){
global$post;
//判断该文章是否设置的缩略图,如果有则直接显示
if(has_post_thumbnail()){
echo the_post_thumbnail();
}else{//如果文章没有设置缩略图,则查找文章内是否包含图片
$content=$post->post_content;
preg_match_all('//sim',$content,$strResult,PREG_PATTERN_ORDER);
$n=count($strResult[1]);
if($n>0){//如果文章内包含有图片,就用第一张图片做为缩略图
echo'';
}else{//如果文章内没有图片,则用默认的图片。
echo'';
}

调用图片:

<?php don_the_thumbnail();?>
方法三:

使用preg_match与preg_match_all来获取内容中所有图片地址.

1、在主题模板的function.php里添加下面的函数:

//截取内容中第一张图片函数

function catch_that_image(){

global $post,$posts;

ob_start();

ob_end_clean();

preg_match('/]*?src=['"]([^'"<>]+?)['"][^<>]*?>/i',$post->post_content,$matche);

if($matche[1])

return $matche[1];

//否则取默认图片

return 'default.gif';

}
2、调动代码如下:

<?php the_title();?>

#现在前往

精选留言

wordpress,判断,文章,是否
sample
2020-12-31
写留言
签到
投稿
QQ咨询
返回顶部