-
-
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.
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
<?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