Skip to content

Instantly share code, notes, and snippets.

@tommaitland
Created December 17, 2013 07:55
Show Gist options
  • Save tommaitland/8001524 to your computer and use it in GitHub Desktop.
Save tommaitland/8001524 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