Skip to content

Instantly share code, notes, and snippets.

@velosipedist
Last active December 19, 2015 09:59
Show Gist options
  • Save velosipedist/5937475 to your computer and use it in GitHub Desktop.
Save velosipedist/5937475 to your computer and use it in GitHub Desktop.
Quick way to list images from Wordpress posts without using "attachment" ("media") posts. Just parse some fresh posts to list found <img/> tags.
<?php
// fetch fresh published posts
$imgPosts = get_posts(array(
'posts_per_page' => 10, // max count
'orderby' => 'post_modified',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
));
// collectin' parsed <img/> tags
$attaches = array();
foreach ($imgPosts as $p => $post) {
// find first <img/> tag found in post body - or go to next post
if(!preg_match('/<img .+(?=\/>)\/>/i', $post->post_content,$matches))
continue;
$attaches[]= $matches[0];
}
// garbagin' useless posts
unset($imgPosts);
// printing collected images
foreach ($attaches as $a => $attach) {
print($attach); // <img src="[image url as written in post]" ... />
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment