Get homepage images without a custom field

admin » 17 May 2009 » In HTML Stuff »

Get homepage images without a custom field

When the first magazine themes arrived a couple of years ago, custom fields were the big thing that drove them. Trouble is, everyone hates filling them out. Thankfully, it is very easy to circumnavigate the need for custom fields with a piece of functions.php code. We’ll also be resizing the image, using phpthumb, the which was used in the example above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
// Get URL of first image in a post
 
function catch_that_image() {
 
global $post, $posts;
 
$first_img = '';
 
ob_start();
 
ob_end_clean();
 
$output = preg_match_all('//i', $post->post_content, $matches);
 
$first_img = $matches [1] [0];
 
// no image found display default image instead
 
if(empty($first_img)){
 
$first_img = "/images/default.jpg";
 
}
 
return $first_img;
 
}

All that is left to do is display the image on the homepage, which we can do with the following code:

1
<img src="<?php bloginfo('template_url'); ?>/phpthumb/phpThumb.php?src=<?php echo catch_that_image() ?>&w=200" alt=""/>

The image will be resized to 200 pixels wide.

Source – WordPress Support Forums

via 10 tricks to make your WordPress theme stand out.

Trackback URL

Comments are closed.