Extract All Image Sources from a WordPress Post

Here’s a handy piece of code that extracts all the images from a WordPress post:

global $post;
if ( preg_match_all(‘/<img (.+?)>/’, $post->post_content, $matches) ) {
foreach ($matches[1] as $match) {
foreach ( wp_kses_hair($match, array(‘http’)) as $attr)
$img[$attr[‘name’]] = $attr[‘value’];
echo $img[‘src’];

The resulting output will be in this form:

[src] => test.jpg
[class] => testclass another
[id] => testid
[fake] =>

About Jean Galea

Jean Galea is a WordPress developer, entrepreneur and padel player. He is the founder of WP Mayor, the plugins WP RSS Aggregator and EDD Bookings, as well as the Mastermind.fm podcast. His personal blog can be found at jeangalea.com.

Related Articles

  • Best Banner Image Plugin for WordPress

    WP Bannerize is an amazing Banner Image Manager. In your template insert: , use new shortcode featured or set it like Widget.

  • How to Remove Image Sizes in WordPress

    In an earlier post about image sizes in WordPress, we had shown you a way to choose which image sizes are available for choosing when you're inserting an image in…

  • Nothing is more effective at capturing the fleeting attention of readers than engaging images. Bloggers do well to pepper their posts with strong imaging, and now there is a way…