In my other blog, Pet Turtles And More, I wanted to display one image from the content of my posts and be able to over-ride that image with another, if I so choose, within the WordPress loop .

The result I wanted (which is what I got) looks like this:
turtle pictures
The first image in the post is displayed or, if I designate an alternate, it will display an alternate image.

The first step I did was find a way to extract the image from a post. I found this in the WordPress.org support forums: Retrieve First Image From Post.

This worked beautifully, but noticed that it:

  1. didn’t give me an easy way to override the image if I didn’t like the one it chose (which is the first image)
  2. if I had an advertisement, even one that is generated by an iframe, it would take the image from the ad and display it instead, and
  3. if I use shortcode to display a gallery (like what is used to display a NextGen Smooth gallery, it wouldn’t be able to extract a photo

So I looked for a way to add an image through the use of custom fields. I found number 9 from Custom Fields Hacks For WordPress to be most useful.

Then I did some nifty PHP to combine the two hacks and came out with this code.

Paste this into your theme’s functions.php file:

function get_custom_field_value($szKey, $bPrint = false) {
	global $post;
	$szValue = get_post_meta($post->ID, $szKey, true);
	if ( $bPrint == false ) return $szValue; else echo $szValue;
}


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];
// no image found display default image instead
if(empty($first_img)){
$first_img = get_custom_field_value('mythumb');
}
return $first_img;
}

And use this within the WordPress loop for where you want to display the image:

<?php   
$customField = get_post_custom_values("mythumb");
if (isset($customField[0])) {
    echo &#039;<img />'; }
  else{
echo '<img src="';
echo (catch_that_image());
echo '" />'; }
 ?&gt;

The code assumes that you are using a custom field called “mythumb” and that you are using the full URL path of the image for “mythumb”.

What the code does is it first tells WordPress to display the image in “mythumb” then if that custom field is empty, it will then display the first image in the post. In effect, it displays the first image in a post or the one in a custom field.

A nice WP hack indeed!!