Skip to content

Instantly share code, notes, and snippets.

@StarWar
Forked from tommaitland/get-first-image.php
Created March 14, 2018 14:52
Show Gist options
  • Save StarWar/fcd15c9dfe7e18629774039de37341a4 to your computer and use it in GitHub Desktop.
Save StarWar/fcd15c9dfe7e18629774039de37341a4 to your computer and use it in GitHub Desktop.
WordPress helper function that retrieves the first image from a post, with basic support for swapping the image size.
<?php
/*
Based on the original CSS-Tricks code (http://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/)
## Usage
Include in functions.php
<?php echo get_first_image('thumbnail'); ?>
*/
function get_first_image($size = false) {
global $post, $_wp_additional_image_sizes;
$first_img = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if (empty($first_img)) {
return;
}
if ($size && $_wp_additional_image_sizes[$size]['crop'] == 1) {
$size = '-' . $_wp_additional_image_sizes[$size]['width'] . 'x' . $_wp_additional_image_sizes[$size]['height'] . '.jpg';
$pattern = '/-\d+x\d+\.jpg$/i';
$first_img = preg_replace($pattern, $size, $first_img);
}
return $first_img;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment