I’m trying to get my WordPress theme to pull up a thumbnail image for each post listed on the index page that I specify in a custom field added to the post in a field that is specified as ‘image’. For whatever reason the get_post_meta() function isn’t returning anything though, try as I might. What am I doing wrong?
Here’s the code:
<?php while (have_posts()) : the_post(); ?>
<div class="posts-wrapper">
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<img src="<?php get_post_meta($post->ID, 'image', true); ?>">
</div>
<?php endwhile; ?>
Since WordPress 2.9, there is a featured images function you can use for thumbnails that is much easier than using custom fields. Here’s how to do it:
Add in functions.php:
Then you just add this wherever you want the thumbnail to display:
And when you’re writing a post, on the far right side of the page, there’s a Featured Images section. Select your image and viola! 🙂
you must echo the return value from the function
get_post_meta()
For wordpress 5.4.2, I fetch meta fields as below and it works. Replace text “image” with your meta_key