2011-08-31 96 views
0

在我的主页,我试图输出每个帖子的第一个图像抽丝第一形象,我能成功地做到这一点在我functions.php中使用此代码:WordPress的:从画廊

function catch_that_image() { 
global $post, $posts; 
$first_img = ''; 
ob_start(); 
ob_end_clean(); 
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
$first_img = $matches [1] [0]; 

if(empty($first_img)){ //Defines a default image 
$first_img = "/images/default.jpg"; 
} 
return $first_img; 
} 

,然后我把它在我的循环是这样的:

<img src=”<?php catch_that_image(); ?>” /> 

这种方法的问题是,如果我把在同一职位的画廊将无法正常工作。我很困惑,因为该帖子的输出仍然呈现img标记,我的假设是,catch_that_image()应该拦截该标记?我的想法不正确吗?有没有更好的方法来处理这个问题?

回答

5

使用WordPress短标签将图库放置在您的文章中。当应用用于转换短标签的过滤器时,将短标签转换为HTML图像标签。

下可能的工作,但我不知道:

function catch_that_image() { 
global $post, $posts; 
$first_img = ''; 
ob_start(); 
ob_end_clean(); 


$transformed_content = apply_filters('the_content',$post->post_content); 


$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $transformed_content, $matches); 
$first_img = $matches [1] [0]; 

if(empty($first_img)){ //Defines a default image 
$first_img = "/images/default.jpg"; 
} 
return $first_img; 
} 

请让我知道这是否是有用的,或者如果它是指向你到正确的方向!

食品链接:

http://codex.wordpress.org/Gallery_Shortcode

http://codex.wordpress.org/Function_Reference/apply_filters

http://codex.wordpress.org/Function_Reference/do_shortcode

+0

这似乎已经奏效!谢谢! –

+0

它呈现图像的文本路径但不是图像本身的任何解决方案? –

+0

我的错误我试图让它没有图像标签:P反正谢谢,但现在我想添加我的自定义大小。任何想法如何做? –