/**
* Get the first image in a post. Strip Version. Retrieve the first image from each post and resize.
*
* @param string $size get the first image size.
* @link https://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/
* see
* Usage: Include in functions.php
* <?php echo get_first_image('thumbnail'); ?> in the page template.
*/
function get_first_image( $size = 'thumbnail' ) {
global $post, $posts;
$first_img = '';
preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', do_shortcode( $post->post_content, 'gallery' ), $matches );
$first_img = isset( $matches[1][0] ) ? $matches[1][0] : null;
if ( empty( $first_img ) ) {
return get_template_directory_uri() . '/assets/images/empty.png'; // path to default image.
}
// Now we have the $first_img but we want the thumbnail of that image.
$explode = explode( '.', $first_img );
$count = count( $explode );
$size = '-624x312'; // Our panel ratio (2:1) 312x156 for lighther page, 624x312 for retina; use add_image_size() and Force Regenerate Thumbnails plugin when changing sizes.
$explode[ $count -2 ] = $explode[ $count -2 ] . '' . $size;
$thumb_img = implode( '.', $explode );
return $thumb_img;
}
add_filter( 'get_first_image', 'thumbnail' );
gist
2 years ago