Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bookchiq/4cb382e8d29ac5b00074 to your computer and use it in GitHub Desktop.
Save bookchiq/4cb382e8d29ac5b00074 to your computer and use it in GitHub Desktop.
WordPress: get the Featured Image or fall back to the first image of a post
function jewish_food_hero_get_best_image( $size = 'full' ) {
$image_data = array();
if ( has_post_thumbnail() ) {
$image_id = get_post_thumbnail_id();
$image_data_raw = wp_get_attachment_image_src($image_id, $size);
$image_data['url'] = $image_data_raw[0];
$image_data['width'] = $image_data_raw[1];
$image_data['height'] = $image_data_raw[2];
} else {
global $post, $posts;
ob_start();
ob_end_clean();
$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches );
$image_data['url'] = $matches[1][0];
}
if ( empty( $image_data ) ) {
$image_data = false;
}
return $image_data;
}
/*
* 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 my_image_display(); ?>
*/
function jewish_food_hero_get_best_image_url( $size = 'full' ) {
$image_data = jewish_food_hero_get_best_image( $size );
return $image_data['url'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment