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:
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:
- 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)
- 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
- 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('//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:
'; } else{ echo ''; } ?>
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!!