Skip to content

Instantly share code, notes, and snippets.

@SilentComics
Last active April 17, 2019 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SilentComics/0a7ea47942eb759dbb48eac2b7be1bbc to your computer and use it in GitHub Desktop.
Save SilentComics/0a7ea47942eb759dbb48eac2b7be1bbc to your computer and use it in GitHub Desktop.
Get the first image in a post; retrieve the first image from each post in WordPress and resize it.
/**
* Get the first image from each post and resize it.
*
* @return string $first_img.
* @link https://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/
* @link https://gist.github.com/SilentComics/0a7ea47942eb759dbb48eac2b7be1bbc/
* Usage: Include in functions.php
* Call <?php echo get_first_image('thumbnail'); ?> in page template.
*/
function get_first_image() {
global $post;
$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' );
@yawarir
Copy link

yawarir commented Feb 12, 2018

very thanks .
how can i force change the url of images that have another size !
like this :
https://yawar.ir/wp-content/uploads/2014/08/yawar-1024x682.jpg
in this case your code can't working correctly .

@SilentComics
Copy link
Author

SilentComics commented Feb 25, 2018

Until a better solution exists, you may want to use the Regenerate Thumbnails plugin when changing sizes.

Edit: Force Regenerate Thumbnails no longer seems maintained.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment