How To Get First Image Link From Posts | WordPress


In this pretty simple tutorial, I’ll show you how to get first image url from wordpress posts and using it in a loop.

This tutorial is a translated version of my Turkish article called WordPress Yazıdaki İlk Resmin URL’sini Alma. If you’re Turkish, read it.

If you don’t use WordPress post thumbnails, I suggest you to use this trick to get post images. Let’s begin.

function get_first_image_url() {
global $post, $posts;
 $first_img = '';
 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
 $first_img= $matches [1] [0];
 if(empty($first_img)){ // if post hasn't a image:
 $first_img = "/path/to/default/img.jpg"; // return default image.
 return $first_img;
Copy and paste it to your theme’s functions.php file.

How to use this function

This functions returns first image’s url, don’t printing it. So you should echo this function to show images.

/* This is a example of index.php file.
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="article">
<img class="post-image" src="<?php echo get_first_image_url(); ?>" alt="<?php the_title(); ?>" />
<h2 class="post-heading"><?php the_title(); ?></h2>
<!-- blah blah blah -->
<?php endwhile; ?>
<?php else : ?>
<?php include("404.php"); ?>
<?php endif; ?>

Also you can use it on Open Graph meta tags.

<meta property="og:image" content="<?php if(is_single()) { echo get_first_image_url(); } ?>" />


Why this function returns image url, not printing? Because, we can use this function to another function’s parameter.

This one is my second English article. I could have grammer mistakes and misspellings. Please write a comment if you have a better function or if you liked this article.

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir