Ever wonder how Wordpress template / site authors post images directly to the index page with the CSS/XHTML already configured for the image? A lot of “magazine style” authors use this method, and I’ll teach you how.
Let’s start off by taking a quick look at our custom field section..

Now all we need is a bit of PHP code to add to our page so that we can call on and apply our image to our index page. I know you could have figured this out, but I’ll say it anyway; You can use this method to post to any page / listing.
1 2 3 4 | <?php while (have_posts()) : the_post(); ?> <?php $image = get_post_meta($post->ID, 'img', true); ?> <?php echo $image; ?> <?php endwhile; ?> |
Let’s examine our code above..
More than likely, you’ll want to display your image within its own CSS class. We simply enclose our php echo function in a line of XHTML, like so..
1 2 3 4 | <?php while (have_posts()) : the_post(); ?> <?php $image = get_post_meta($post->ID, 'img', true); ?> <img class="yourimageclass" src="<?php echo $image; ?>" alt="Our Image" /> <?php endwhile; ?> |
You could also define an image to use as a default image, just in case we didn’t post an image with our post either by accident or on purpose.
1 2 3 4 5 6 7 | <?php while (have_posts()) : the_post(); ?> <?php $image = get_post_meta($post->ID, 'img', true); ?> <?php if(empty($image)) { $image = "http://www.anydomain.com/img/document.png"; } ?> <img class="yourimageclass" src="<?php echo $image; ?>" alt="Our Image" /> <?php endwhile; ?> |
And that’s it, folks! I hope this helps you create all those wonderful Wordpress templates, or it helps to make your website that much more dynamic.