Need to grab a featured image via URL and then thumnail or a custom image size? Place these two code snippets in your functions file to do the follow:
1 - Get the featured image, if there is no featured image set, then get the first image that appears in the post editor, if there is no image there, use the default noimage.jpg
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// GET THE FIRST IMAGE 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); if (isset($matches[1][0])){ $first_img = $matches[1][0]; } if(empty($first_img)){ //Defines a default image $first_img = get_template_directory_uri() . "/images/noimage.jpg"; } return $first_img; } |
2 - Find the proper featured image url from the size of your choosing, if there is no featured image, grab the correct size from the previous function.
1 2 3 4 5 6 7 8 9 10 11 |
// Logic to get the correct image size function featured_url($size){ global $post, $posts; $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size ); if (has_post_thumbnail()){ $url = $image['0']; } else { $url = catch_that_image(); } return $url; } |