Forked from brajeshwar/wordpress-post-thumbnail-or-first-image-or-default.php
Last active
September 17, 2017 12:52
-
-
Save DediData/909110da712fd3ca51045d044ce3fd8b to your computer and use it in GitHub Desktop.
Wordpress - Get the Image from Post Thumbnail or the First Image of a post or else use a default Image.
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 | |
/* | |
* Display Image from the_post_thumbnail or the first image of a post else display a default Image | |
* Chose the size from "thumbnail", "medium", "large", "full" or your own defined size using filters. | |
* USAGE: <?php echo get_post_image_url(); ?> | |
*/ | |
function get_post_image_url($size = 'full') { | |
if (has_post_thumbnail()) { | |
$image_id = get_post_thumbnail_id(); | |
$image_url = wp_get_attachment_image_src($image_id, $size); | |
$image_url = $image_url[0]; | |
} else { | |
global $post, $posts; | |
$image_url = ''; | |
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); | |
$image_url = (isset($matches[1][0]))? $matches[1][0] : get_bloginfo('template_url') . "/img/default.jpg"; | |
} | |
return $image_url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment