Skip to content

Instantly share code, notes, and snippets.

@fencermonir
Created May 12, 2020 20:26
Show Gist options
  • Save fencermonir/452abb1ba63cdd69f24d5b480c5153f7 to your computer and use it in GitHub Desktop.
Save fencermonir/452abb1ba63cdd69f24d5b480c5153f7 to your computer and use it in GitHub Desktop.
Get the first image of post content.
<?php
/**
* Get the first image of post content by post_id
*/
function catch_the_first_image($post_id)
{
$first_img = '';
$content_post = get_post($post_id);
$content = $content_post->post_content;
$output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $content, $matches);
$first_img = $matches[1][0];
if (empty($first_img)) {
$first_img = get_stylesheet_directory_uri() . '/img/imageplaceholder.png';
}
return $first_img;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment