Skip to content

Instantly share code, notes, and snippets.

@jartes
Created September 20, 2012 10:17
Show Gist options
  • Save jartes/3755078 to your computer and use it in GitHub Desktop.
Save jartes/3755078 to your computer and use it in GitHub Desktop.
Get First Image from a WordPress Post
get_thumbnail_image_src() {
/**
* @todo
* * Return or echo
*
*
*/
global $post;
if ( has_post_thumbnail( $post->ID ) ) {
$src = wp_get_attachment_image_src( get_post_thumbnail_id() );
return $src;
}
$first_img = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = get_bloginfo('template_directory') . "/images/default.jpg";
}
return $first_img;
}
@jartes
Copy link
Author

jartes commented Sep 20, 2012

This function retrieves the source of the first image of a WordPress post. But if the post have a post thumbnail, it will return the source of it.

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