我想从the_content()中提取图像,并希望在index.php上显示来自post的第一个图像,并希望在single.php上显示所有图像。为此,我在the_content()上应用了一个过滤器:
<?php
/*****************************************************************************
Post Summary Filter - Grap Image Thumbnails, Strip Tags, etc
******************************************************************************/
add_filter('the_content', 'filterContentSummary', 0);
function filterContentSummary($content){
global $post;
if( is_home() || is_category() || is_tag() || is_author() || is_date() || is_search() || is_single ){
//if NOT single page or "page" page
$img=''; //default img code
$final_width = 300;
$content = $post->post_content;
//search for first image in article
preg_match('/<img[^>]*>/i',$content,$matches);
//image found, process it
if($matches){
preg_match('/src="[^"]*"/i',$matches[0],$src);
preg_match('/width="(\d*)[^"]*"/i',$matches[0],$width);
if($width[1] < $final_width){
$final_width = $width[1];
}
}
//prepare text
if(!empty($post->post_excerpt)){
$content = $post->post_excerpt;
}else{
//strip shortcodes, tags
$content = preg_replace('/\[\/*[^\]]*\]/i', '', $content); //cont is ready
$content = preg_replace('/<[^>]*>/i', '', $content); //cont is ready
$content = substr($content,0,500);
$content = explode(". ", $content);
array_pop($content);
$content = implode(". ", $content) . "";
}
if($content=="."){
$content = $post->post_content;
}
//prepare final content
$content = "<p>". $content ."</p>";
//Adding Read more link
$content .= "<p align='right' class='seemore'><a href=". get_permalink() . "></a></p>";
}
// Make sure to return the content
return $content;
}
?>
在使用正则表达式的index.php上,我找到帖子中的第一个图像并显示它:
<?php while (have_posts()) : the_post();
$content = $post->post_content;
preg_match_all('/(<img.*src="(.*)"[^>]*>)/iU',$content,$matches);
?>
现在$matches
拥有所有图片:
<div class="content-img"><img src="<?php echo $matches[2][0];?>"/></div>
...用于在帖子上显示第一张图片。
但我如何在single.php上显示所有图像?
答案 0 :(得分:3)
在global $post
之后只需添加if(is_single()) return $content;
,如果它是单个模板,则过滤器将返回包含所有图像的原始内容...然后正常显示。