Find first image URL in WordPress post content

Find first image URL in WordPress post content

Created:29 Dec 2016 06:59:28 , in  Web development

Find first image URL in the article with PHP.


function find_first_image_src($post) {
    $matches = array();
	preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	return count($matches[1]) > 0 ? $matches[1][0] : NULL;
}

Usage


if(isset(find_first_image_src($post))){
    //do stuff here ...
}else{
    // no image found in the post contents
}

$post variable is a WordPress $post object. It is available through global variable $post.


global $post;
$first_img_url = find_first_image_src($post);

or if you need a post with a specific ID instead of the current post, you can get it with get_post() as follows:


$post = get_post(get_the_ID());
if( isset($post) ){
  $first_img_url = find_first_image_src($post);
  // do stuff with first_img_url 
}  

More than one image URL

The above technique can be easily adapted to find not only the first image URL but any post image URL. Just replace 0 in $matches[1][0] with whatever number you need (since $matches[1] is a PHP array, matches are 0 indexed), if you need all the post image URLs, just grab $matches[1].

This post was updated on 06 Oct 2021 20:42:32

Tags:  image ,  php ,  wordpress 


Author, Copyright and citation

Author

Sylwester Wojnowski

Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.

Copyrights

©Copyright, 2022 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.

Citation

Cite this article as:

Wojnowski, Sylwester. "Find first image URL in WordPress post content." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/find-first-image-url-in-wordpress-post-content

Add Comment

Allowed BB Code - style tags: [b][/b], [i][/i], [code=text][/code],[code=javascript][/code],[code=php][/code],[code=bash][/code],[code=css][/code],[code=html][/code]


I constent to processing my data given through this form for purposes of a reply by the administrator of this website.

Recent Comments

Nobody has commented on this post yet. Be first!