Created
May 12, 2020 20:26
-
-
Save fencermonir/452abb1ba63cdd69f24d5b480c5153f7 to your computer and use it in GitHub Desktop.
Get the first image of post content.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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