Put the following code inside the functions.php file or in your plugin file.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function dcsGetFirstImageFromPost() { 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; } |
Use the following code inside the loop
1 2 3 4 5 6 7 8 9 10 11 |
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 dcsGetFirstImageFromPost(); echo '" alt="" />'; echo '</a>'; } |