Skip to content

Instantly share code, notes, and snippets.

@michaelwilhelmsen
Created May 9, 2014 11:00
Show Gist options
  • Select an option

  • Save michaelwilhelmsen/299da2e4f96d5e3ffb37 to your computer and use it in GitHub Desktop.

Select an option

Save michaelwilhelmsen/299da2e4f96d5e3ffb37 to your computer and use it in GitHub Desktop.
Using the built in Simplepie library in Wordpress, this function fetches the first img of each post. Display it using: echo '<img src="' .get_first_image_url($item->get_content()). '"/>';
/**
* Gets RSS Image Item Link
*
* Place the following inside rss markup
* to display the the first image of that post:
* echo '<img src="' .get_first_image_url($item->get_content()). '"/>';
*
*/
function get_first_image_url($html) {
if (preg_match('/<img.+?src="(.+?)"/', $html, $matches)) {
return $matches[1];
}
else return 'url_of_default_image.jpg';
}
@purzlbaum
Copy link
Copy Markdown

Why do you use Simplepie for it?

@michaelwilhelmsen
Copy link
Copy Markdown
Author

I was using it to fetch featured image from a feed I didn't own, which means I couldn't change the output and the feed wasn't getting the featured images (so I couldn't use get_featured_image). So I ended up with this solution where I took the first image of each post instead and used that as my featured image.

@michaelwilhelmsen
Copy link
Copy Markdown
Author

Is there easier ways of doing this?

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