Created
July 18, 2014 11:58
-
-
Save tjhole/fc498090203536b23654 to your computer and use it in GitHub Desktop.
WORDPRESS: Get first image from post
This file contains hidden or 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
if ( get_the_post_thumbnail($post_id) != '' ) { | |
echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">'; | |
the_post_thumbnail(); | |
echo '</a>'; | |
} else { | |
echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">'; | |
echo '<img src="'; | |
echo catch_that_image(); | |
echo '" alt="" />'; | |
echo '</a>'; | |
} |
This file contains hidden or 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
function catch_that_image() { | |
global $post, $posts; | |
$first_img = ''; | |
ob_start(); | |
ob_end_clean(); | |
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); | |
$first_img = $matches[1][0]; | |
if(empty($first_img)) { | |
$first_img = "/path/to/default.png"; | |
} | |
return $first_img; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment