开发者

WordPress: snag first image from a gallery

开发者 https://www.devze.com 2023-03-31 22:47 出处:网络
On my homepage, I\'m trying to output the first image of each post, and I\'m able to successfully do that using this code in my functions.php:

On my homepage, I'm trying to output the first image of each post, and I'm able to successfully do that using this code in my functions.php:

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(emp开发者_如何学Goty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}

and then I call it in my loop like this:

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

The problem with this method is that it won't work if I place a gallery in that same post. I'm confused because the output of the post still renders the img markup, and my assumption is that catch_that_image() should snag that markup? Is my thinking incorrect? Is there a better way to handle this?


The gallery is placed inside your post using a WordPress short-tag. The shorttag is transformed into HTML-image tags when the filter for transforming the shorttag is applied.

The following might work, but I am not sure:

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;
}

Please let me know if this was useful or if it was pointing you into the right direction!

Codex Links:

http://codex.wordpress.org/Gallery_Shortcode

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消