Last active
April 17, 2019 12:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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' ); |
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
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 .